Brightlane's shipping team needs each order flagged by urgency. The mapping is:
pending→'action needed'shipped→'in transit'delivered→'complete'- Any other status →
'unknown'
Write a query to return each order's ID, status, and urgency label.
Assumptions:
- The
orderstable contains every order Brightlane has processed. - The four bullets above are exhaustive — every order maps to one of the four labels.
Output:
- One row per order, with columns
id,status, andurgency.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
status,
CASE
WHEN status = 'pending' THEN 'action needed'
WHEN status = 'shipped' THEN 'in transit'
WHEN status = 'delivered' THEN 'complete'
ELSE 'unknown'
END AS urgency
FROM
orders The shape
Three WHEN branches handle the three known statuses, and ELSE 'unknown' catches anything outside that set. The mapping in the prompt translates directly into the CASE, one branch per status.
Clause by clause
SELECT id, statusreturns the order ID and its raw status, so the input (the raw status) sits next to the output (the urgency label).WHEN status = 'pending' THEN 'action needed'is the first branch. PostgreSQL tests the condition against the current row'sstatus; if it matches the literal'pending', the expression returns'action needed'and the rest of the branches are skipped.WHEN status = 'shipped' THEN 'in transit'andWHEN status = 'delivered' THEN 'complete'are the same shape for the other two known statuses. PostgreSQL walks the branches top to bottom and stops at the first match.ELSE 'unknown'is the catch-all. Any order whosestatusdoesn't match one of the three literals — cancelled, refunded, anything outside the enumerated set — lands here.END AS urgencycloses the expression and labels the derived column.FROM ordersis the source set.
Because the three known conditions are mutually exclusive (a status equals exactly one string), branch order doesn't affect the answer here. That changes the moment branches can overlap, which is what range-based CASE expressions force you to think about.
You practiced chaining multiple WHEN branches to encode a many-to-one mapping. PostgreSQL evaluates the branches top-to-bottom and returns the first match — ELSE catches everything that didn't match any earlier branch.