SQL · Level 1 Logic

SQL CASE WHEN

Label each order small, medium or large with CASE WHEN, and order the conditions so the first match is the right one.

  • CASE WHEN ... THEN ... ELSE ... END
  • The first matching WHEN wins
  • Thresholds from biggest to smallest

CASE WHEN ... THEN ... ELSE ... END picks a value row by row, like if / else. Trap: the first matching WHEN wins, so a loose condition placed first hides the ones below it. Test the strictest condition first.

SELECT name,
  CASE WHEN stock = 0 THEN 'sold out'
       WHEN stock < 5 THEN 'low'      -- placed first, sold out would say 'low'
       ELSE 'ok' END AS status
FROM products;

Return each order's id and a label for its total: 'large' from 100, 'medium' from 30, otherwise 'small', ordered by id. In the database below, an order of exactly 30 is medium.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

orders 5 rows
idINTEGERtotalREAL
1150.0
230.0
329.99
4100.0
55.0
solution.sql
Test Suites Pending
Output