Stop 05 · Aggregation & GroupingTopics · 6/9

Conditional Aggregation with CASE

Part of the SQL Roadmap

In short

"Show delivered, cancelled and returned counts side by side, per city." Without this trick you'd run three queries and paste them together. With CASE inside an aggregate, it's one pass.

Putting CASE inside an aggregate, like SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END), lets you calculate several filtered totals in one pass.

The jaadu sits in a wooden scorer's box beside a cricket ground, making tally marks with three different coloured pencils as a ball flies over the boundary.

Think of it like this

The cricket scorer's sheet

A scorer at a Ranji match doesn't watch the game three times, once for fours, once for sixes, once for dot balls. One pass, one sheet with three columns, and each ball adds a mark to the right column. SUM(CASE WHEN ...) is that scoresheet: every row is looked at once and dropped into the right tally.

Watch it happen

Tallying six order statuses in one pass

delivered
0
returned
1
delivered
2
cancelled
3
delivered
4
returned
5

1/5Six orders from Jaipur. We want three counts as three columns.

The big ideas

What you need to know

CASE turns rows into 1 or 0

CASE WHEN status = 'returned' THEN 1 ELSE 0 END marks each row. SUM adds the marks.

Many filters, one query

Each CASE is a column with its own condition, so one GROUP BY gives several filtered totals.

Sum amounts too

SUM(CASE WHEN payment = 'UPI' THEN amount ELSE 0 END) gives UPI revenue next to card revenue.

FILTER in PostgreSQL

COUNT(*) FILTER (WHERE status = 'returned') is a cleaner way to say the same thing in PostgreSQL.

See it in code

Walk through the code

sql
1SELECT2  city,3  COUNT(*) AS orders,4  SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,5  SUM(CASE WHEN status = 'returned'  THEN 1 ELSE 0 END) AS returned,6  COUNT(*) FILTER (WHERE status = 'cancelled')        AS cancelled,7  ROUND(8    100.0 * SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) / COUNT(*),9    110  ) AS return_rate_pct11FROM orders12GROUP BY city13ORDER BY return_rate_pct DESC;

1/4Each CASE gives 1 or 0 per row, and SUM adds them up within the city.

Status counts and return rate per city in one query. FILTER works in PostgreSQL and SQLite. In MySQL and SQL Server, stick to the SUM(CASE ...) form.

Save yourself the pain

Common mistakes

Oops

COUNT(CASE WHEN status = 'returned' THEN 1 ELSE 0 END)

Do this instead

COUNT counts the zeros too, because 0 is not NULL. Use SUM with ELSE 0, or COUNT with no ELSE (which gives NULL).

Oops

100 * returned / orders giving 0 for every city.

Do this instead

Both sides are integers, so PostgreSQL does integer division. Write 100.0 * ... to get decimals.

Oops

Running three separate queries with WHERE status = ... and joining them.

Do this instead

One pass with conditional aggregation is shorter, faster and can't go out of sync.

Your mission

Payment mix report

~20 min

Quick check

What does SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) return for a group with 8 orders, 2 of them cancelled?

Go deeper

  1. 1Count delivered, cancelled and returned orders as separate columns in one query.
  2. 2Calculate a return rate per category with conditional aggregation.
  3. 3Learn PostgreSQL's FILTER (WHERE ...) as a cleaner alternative.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge