← SQL and databases

If-then labels with CASE

Turn numbers into words like short, medium, long.

Start this lesson

CASE lets a query make choices, like "if … then … else" in everyday speech. CASE WHEN condition THEN value WHEN other_condition THEN value ELSE value END. SQL checks the WHEN lines from top to bottom and uses the first one that is true. ELSE covers everything else.

SELECT title,
  CASE WHEN pages < 200 THEN 'short'
       WHEN pages < 350 THEN 'medium'
       ELSE 'long' END AS size
FROM books;

A 190-page book is short. A 288-page book fails the first test but passes the second, so it is medium. 412 pages fails both, so it is long.

Because the first true WHEN wins, order matters. Put the most specific or strictest test first.

Without ELSE, rows that match no WHEN get NULL.