NO. 08 · 7 exercises

8. Conditional Logic

CASE, COALESCE, and queries that make decisions.

The lesson

Conditional Logic

So far your queries have been answering what questions: which tracks, how many, in what order. But a real catalog is full of it depends questions. Is this song cheap or premium? Is this artist a veteran or a newcomer? Should this album get a badge?

SQL answers those with conditional logic: expressions that look at a value and decide what to put in the answer. This chapter is short — four tools — but they're the difference between exporting data and reporting on it.

One value, two answers: CASE WHEN

CASE is an expression: give it a condition, and it returns one value when the condition is true and another when it's false.

SELECT title, unit_price,
       CASE WHEN unit_price > 1.00 THEN 'premium'
            ELSE 'standard' END AS tier
FROM tracks;

Every row's unit_price is inspected: over 1.00 gets 'premium', everything else gets 'standard'. The whole CASE ... END is one column, exactly like duration_sec / 60.0 was back in chapter 1 — just computed by a question instead of arithmetic.

Two notes:

  • The ELSE is optional. Leave it out, and rows that fail the condition quietly get NULL. Usually you want to say what you mean and include it.
  • The quoted words are your choice. They're text labels, not SQL — the store could call them 'expensive' and 'cheap' and the query would work the same.

More branches: searched CASE

One WHEN handles two cases. Real life has more, and you can stack conditions:

SELECT title, duration_sec,
       CASE WHEN duration_sec < 200 THEN 'short'
            WHEN duration_sec < 300 THEN 'medium'
            ELSE 'long' END AS length
FROM tracks;

This reads like a checklist, and it's evaluated exactly like one: top to bottom, first match wins. A 150-second song hits the first WHEN and stops; a 250-second song misses the first, matches the second, and stops. Order matters, so check the narrow conditions first. This form is called a searched CASE, because each WHEN carries its own condition rather than testing one expression repeatedly.

Filling the holes: COALESCE

NULL is contagious: any expression that touches it usually becomes NULL. Chapter 2 taught you to filter around it; this chapter is about taming it — replacing NULL with a sensible stand-in when you present the answer.

SELECT name, country, COALESCE(formed_year, 'Unknown') AS formed_year
FROM artists;

Two of our artists — Nocturne Quartet and The Paper Cranes — have no formed_year, so their rows show 'Unknown' instead of a blank.

COALESCE takes any number of arguments and returns the first one that isn't NULL. That makes it a natural chain of fallbacks: COALESCE(phone, mobile, email, 'no contact on file'). It works on any type, and it doesn't mind mixing a number (the year) with text (the fallback).

The same trick tames foreign keys that point nowhere. Two customers have support_rep_id = NULL:

SELECT first_name, last_name, COALESCE(support_rep_id, 0) AS rep
FROM customers;

Here the fallback is a number, 0, meaning "no rep assigned". This exact pattern comes back in the boss exercise.

Erasing sentinel values: NULLIF

COALESCE replaces NULLs. NULLIF(a, b) does the reverse: it returns NULL when a equals b, and a otherwise. The classic job is cleaning up sentinel values — a special value that really means "none of the above".

The store's default price is 0.99. Want a catalog where only special pricing stands out?

SELECT title, NULLIF(unit_price, 0.99) AS special_price
FROM tracks;

Every 0.99 row comes back as NULL — thirty-five holes in one column, and only the fourteen 1.29 tracks survive with a number.

Its other famous job is guarding against division by zero:

SELECT title, unit_price / NULLIF(duration_sec, 0) AS price_per_second
FROM tracks;

If duration_sec were ever 0, NULLIF turns it into NULL, and dividing by NULL gives NULL instead of an error. None of our rows is 0 today, but the query is safe against bad data forever — that's the point of the guard.

One line instead of five: IIF

CASE is wordy for a single yes/no question, so SQLite provides a shorthand:

SELECT title, IIF(duration_sec < 210, 'quick', 'regular') AS pace
FROM tracks;

IIF(condition, value_if_true, value_if_false) is exactly the two-branch CASE squeezed onto one line. Nothing more, nothing less — a typing shortcut, not a new idea.

CASE goes everywhere

CASE isn't just for SELECT lists. It's an expression, and expressions work in ORDER BY — and inside aggregates.

Conditional counting. Want several counts in one go? SUM of a CASE that yields 1 or 0 counts matches:

SELECT genre_id,
       SUM(CASE WHEN unit_price > 1.00 THEN 1 ELSE 0 END) AS premium,
       SUM(CASE WHEN unit_price <= 1.00 THEN 1 ELSE 0 END) AS budget
FROM tracks
GROUP BY genre_id;

Each track's price gets classified twice, and the 1s add up: one row per genre, two counts side by side, no extra work.

Cleaning the group key. GROUP BY buckets NULLs into a group of their own — fine in a database, cryptic in a report. COALESCE the key:

SELECT COALESCE(support_rep_id, 0) AS rep,
       COUNT(*) AS customers
FROM customers
GROUP BY support_rep_id;

Group on the raw column, display the cleaned one. The two unassigned customers now show up under rep 0 instead of an empty label.

Custom sorts. ORDER BY sorts numbers and text, but what if you want a curated order? Assign ranks with CASE, then sort by the rank:

SELECT name
FROM genres
ORDER BY CASE WHEN name = 'Bossa Nova' THEN 0
              WHEN name = 'Classical' THEN 1
              ELSE 2 END, name;

The owner's two favorites get ranks 0 and 1; everything else ties at 2 and falls back to alphabetical order. This is the standard "featured items first" trick.

What you just learned

  • CASE WHEN cond THEN value ELSE value END returns one value or another per row; stack WHENs for multiple branches, narrow conditions first.
  • COALESCE(a, b, ...) returns the first non-NULL argument — the universal "fill the hole" tool.
  • NULLIF(a, b) returns NULL when a equals b — for sentinel values and zero-division guards.
  • IIF(cond, then, else) is the one-line shorthand for a two-branch CASE.
  • CASE composes: inside aggregates (SUM(CASE WHEN ... THEN 1 ELSE 0 END)) and inside ORDER BY (rank, then sort).

Dialect note. CASE, COALESCE and NULLIF are standard SQL — they behave identically in PostgreSQL, MySQL and SQL Server. IIF is the exception: it's SQLite-specific. Standard SQL writes the same idea as CASE WHEN ... THEN ... ELSE ... END, and most writers use CASE everywhere anyway.

Time for the exercises. They build on everything so far — WHERE, GROUP BY, dates — and now the power of "it depends".