skipnothing/SQL

CASE, COALESCE, Casts

One order row has a blank where its amount should be, another divides by a zero count, and a third arrived as the text '42'. The same query must return a sensible value for every row, dropping none.

  • ▸Leave off the fallback branch and every unmatched row quietly comes back blank, surfacing later in a dashboard.
  • ▸Two functions make opposite trades: one swaps a blank for a value, the other a value for a blank.
  • ▸The database won't silently turn a text column holding '42' into the number 42; cross-type math waits until you ask.
BUILDS ON
01

Label each row with CASE

Take four rows of the orders table: the question is which size bucket each one falls into. A CASE expression answers it one row at a time. It walks its branches from the top: the first WHEN whose test comes out TRUE wins, its THEN value becomes the answer for that row, and the rest of the branches are skipped. If nothing matches, the ELSE value is used.

SELECT id, amount,
  CASE WHEN amount >= 50 THEN 'large'
       WHEN amount > 0  THEN 'small'
       ELSE 'none' END AS size
FROM orders;

Four rows go in and four rows come out. Nothing is filtered: the expression does not decide which rows appear, only what value sits in the new size column for each. Row 101 (42.00) fails the first test, passes the second, and lands on 'small'. Row 103 (99.00) takes 'large' on the first test and never looks at the others. The row with a blank amount slips past both tests and falls to the ELSE, which is the thread the next part pulls on.

ORDER THE BRANCHES TO HIT THE TARGET

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL