Sql - CASE WHEN
Code Life
By Pierre Marsaa
CASE WHEN: if / else in SQL
So far, every column you displayed came straight from the table or from a calculation. CASE lets a query choose a value depending on a condition — it is the if / else of SQL.
Meet the battle records of the lab. Notice the nickname column (mostly empty), the wins and losses columns, and Shadowchu's unknown power:
Loading data...
Let's label each Codémon according to its power:
↗️
Loading editor...
↶
↷
SQL reads the WHEN conditions from top to bottom and stops at the first one that is true. When none is true, the ELSE value is used.
Anatomy of a CASE
CASE WHEN condition THEN value WHEN other_condition THEN other_value ELSE default_value END. The whole block is one expression, so give it an alias like any computed column — and never forget the END!
Verify