






Teams often need to categorize rows, clean outputs, or build conditional metrics directly in SQL. CASE WHEN is one of the most common tools for adding business logic to a query without changing the underlying data.
Explain how you would use CASE WHEN in a SQL query. In your answer, cover:
CASE WHEN doesSELECT, WHERE, and ORDER BYNULL values interact with CASE WHENThe interviewer expects a practical explanation with simple PostgreSQL examples. You should describe the syntax, common use cases, and a few mistakes to avoid, rather than giving a highly theoretical answer.
CASE WHEN lets you return different values based on conditions, similar to if/else logic in programming. It is commonly used to create derived columns such as status labels, buckets, or flags.
SELECT order_id,
amount,
CASE
WHEN amount >= 100 THEN 'high_value'
ELSE 'standard'
END AS order_type
FROM orders;
CASE WHEN is often placed inside aggregate functions like SUM or COUNT to calculate metrics for specific subsets of data in a single query. This is a standard pattern for reporting and dashboard queries.
SELECT
SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) AS completed_revenue,
COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled_orders
FROM orders;
CASE WHEN can appear in different parts of a query, but its role changes depending on where it is used. In SELECT, it transforms output values; in ORDER BY, it customizes sorting; in WHERE, it is usually less readable than direct boolean conditions.
SELECT customer_name, status
FROM orders
ORDER BY CASE
WHEN status = 'priority' THEN 1
WHEN status = 'standard' THEN 2
ELSE 3
END;
CASE WHEN does not treat NULL as equal to anything, including another NULL. You must explicitly check IS NULL or IS NOT NULL when you want to branch on missing values.
SELECT order_id,
CASE
WHEN shipped_at IS NULL THEN 'not_shipped'
ELSE 'shipped'
END AS shipping_status
FROM orders;