How do you use the 'CASE' statement in SQL?
Instruction: Provide an example query that uses a CASE statement to return custom status messages based on 'order_status' values.
Context: This question tests the candidate's ability to use conditional logic in SQL queries through the CASE statement, allowing for complex decision making within a query.
Updated
Official answer
CASE is a conditional SQL expression. This example maps order-status values to display messages while distinguishing missing from unrecognized status:
SELECT order_id,
CASE
WHEN order_status IS NULL THEN 'Status missing'
WHEN order_status = 'pending' THEN 'Awaiting processing'
WHEN order_status = 'shipped' THEN 'On the way'
WHEN order_status = 'delivered' THEN 'Delivered'
ELSE 'Unknown status'
END AS status_message
FROM orders
ORDER BY order_id;
Conditions are tested in order and the first true branch supplies the result. The result expressions must have compatible types. Omitting ELSE yields NULL when no condition matches.
Use a defined status vocabulary; a display message does not validate or repair the underlying value. In particular, do not let missing or out-of-range input fall through to a favorable label by accident. This query changes only the result, not stored status data.