AnalystPracticeGuides
DashboardSign up

SQL CASE WHEN

CASE WHEN adds if/then logic to a query: it checks conditions in order and returns the value of the first one that is true. It is how you label rows, build price bands and count several categories at once.

Watch it solved. Task 7: label rows with CASE WHEN, from 5:15, in our video “Data Analyst Interview Questions and Answers: 10 SQL + Excel Tasks, Solved”. Pressing play loads the video from YouTube (privacy). Open on YouTube

How do you label rows?

SELECT name, amount,
CASE
WHEN amount >= 1000 THEN 'large'
WHEN amount >= 100 THEN 'medium'
ELSE 'small'
END AS size
FROM orders;

The order matters. If the 100 check came first, every large order would be labelled medium.

How do you count categories in one query?

SELECT
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid,
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded
FROM orders;

This "pivots" the categories into columns.

Can you group by a CASE?

Yes, repeat it in GROUP BY or group by its alias where the database allows it, for example to count orders per size band.

The ELSE trap

Without ELSE, rows that match no condition get NULL. That's fine for labels but changes the result inside SUM or AVG, so add ELSE 0 when you count.

Try it yourself. Practise this in a real database in your browser, with instant feedback.
Practise CASE

Updated November 2026.

← All free guides