CASE is SQL’s if-then-else. It works through a list of conditions in order and returns the value for the first one that holds. If none holds, it returns the ELSE value, or NULL when there is no ELSE.
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE other_resultENDA CASE expression can go anywhere a value can: in the SELECT list, in ORDER BY, or inside a function. The examples use the tables from the example database.
Sorting values into bands
Section titled “Sorting values into bands”To label each production by the size of its budget:
SELECT Title, Budget, CASE WHEN Budget >= 10000000 THEN 'Large' WHEN Budget >= 3000000 THEN 'Medium' ELSE 'Small' END AS BandFROM ProductionsORDER BY Budget DESC;| Title | Budget | Band |
|---|---|---|
| The Lantern Keepers | 18,500,000 | Large |
| Six Bells | 11,000,000 | Large |
| Quarry Lane | 7,200,000 | Medium |
| Saltmarsh | 3,900,000 | Medium |
| Fennick’s Return | 850,000 | Small |
Order matters. Six Bells, on 11 million, meets both the first and the second condition, but the first one that holds wins, so it is labelled Large.
Turning a value into a label
Section titled “Turning a value into a label”CASE can describe what a value means. Here an empty paid date becomes “Unpaid”:
SELECT InvoiceID, Supplier, CASE WHEN PaidDate IS NULL THEN 'Unpaid' ELSE 'Paid' END AS StatusFROM Invoices;| InvoiceID | Supplier | Status |
|---|---|---|
| 1001 | Hartwell Lighting | Paid |
| 1002 | Kestrel Catering | Paid |
| 1003 | Ashby Camera Hire | Unpaid |
| 1004 | Kestrel Catering | Unpaid |
Splitting a total by condition
Section titled “Splitting a total by condition”Inside SUM(), a CASE adds up only the rows that meet its condition, and counts the rest as zero. This gives several totals in one pass, side by side, which is a common shape for a finance report:
SELECT SUM(CASE WHEN PaidDate IS NULL THEN 0 ELSE Amount END) AS Paid, SUM(CASE WHEN PaidDate IS NULL THEN Amount ELSE 0 END) AS OutstandingFROM Invoices;| Paid | Outstanding |
|---|---|
| 27,780.00 | 44,190.00 |