Skip to content
Bronze 6 min read · Aggregation 3 practice problems ↓

Conditional aggregates and COUNT DISTINCT

A report often needs several counts side by side: all orders, delivered orders, cancelled orders, per restaurant. Running one query per count is slow and clumsy. Conditional aggregates count only the rows that match a condition, so one query gives you every column at once.

Foundations · SQL for data engineers · Bronze · Summarising, lesson 2 of 2

Read first: GROUP BY and HAVING · CASE WHEN and expressions (skip if you know them)

In plain words first

Think of a cashier counting a stack of receipts once, with three tally columns on a notepad: one mark for every receipt, one more only if it was delivered, one more only if it was cancelled. One pass through the stack, three numbers at the end.

A conditional aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → is one of those tally columns: a count or a sum that only counts the rows matching its own condition, while the other columns count theirs.

Several counts in one pass

A report often wants several numbers per group: all orders, delivered orders, cancelled orders. WHERE can only filter the whole query once. Conditional aggregates filter inside each aggregate, so one GROUP BY gives you every number side by side.

Spark SQL · Three ways to count some of the rows

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenullNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more →delivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT restaurant,
       count(*) AS orders,
       count_if(status = 'delivered') AS delivered,
       sum(amount) FILTER (WHERE status = 'delivered') AS delivered_revenue,
       sum(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY restaurant
ORDER BY restaurant

All three styles do the same job. Pick by where the query must run:

StyleExampleWorks in
CASE inside the aggregatesum(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)Every database. The interview-safe answer.
FILTER clausesum(amount) FILTER (WHERE status = 'delivered')Spark, PostgreSQL, SQLite. Clearest to read.
count_ifcount_if(status = 'delivered')Spark, Databricks, Snowflake; BigQuery calls it COUNTIF.

Pizza Lab's delivered revenue is NULL: its only delivered order is 103, which has no amount. That is the SUM rule from the NULL lesson again.

Watch out: count(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) is a classic bug: COUNT counts every non-NULL value, and 0 is not NULL, so it counts every row. Either use SUM with ELSE 0, or COUNT with no ELSE (so non-matching rows are NULL).

Rows into columns

One conditional aggregate per value turns a column of statuses into a row of counts. This is how most "pivot" questions are answered by hand:

Spark SQL · Statuses per city, one column each

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT city,
       count(*) FILTER (WHERE status = 'delivered') AS delivered,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
       count(*) FILTER (WHERE status = 'refunded') AS refunded,
       count(*) FILTER (WHERE status IS NULL) AS unknown
FROM orders
GROUP BY city
ORDER BY city

The unknown column matters: a plain status = ... test can never catch the NULL status of order 104, so it needs its own IS NULL. Spark also has a PIVOT clause that builds these columns for you; the Gold lesson on pivots covers it.

COUNT(DISTINCT): unique values

count(DISTINCT customer_id) counts how many different customers ordered, however many times each one did:

Spark SQL · Orders against unique customers

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT restaurant,
       count(*) AS orders,
       count(DISTINCT customer_id) AS customers
FROM orders
GROUP BY restaurant
ORDER BY restaurant

COUNT(DISTINCT) skips NULLs, like COUNT(column). On very large tables it is expensive, because every unique value must be tracked. approx_count_distinct(customer_id) uses a small sketch (HyperLogLog++) and by default stays within about 5% (you can ask for tighter), which is fine for dashboards and not for billing.

Rates and percentages

A rate is one conditional count divided by another:

Spark SQL · Delivered share per restaurant

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT restaurant,
       round(100 * count_if(status = 'delivered') / count(*), 1) AS delivered_pct
FROM orders
GROUP BY restaurant
ORDER BY restaurant

Two traps hide in that division. First, integer division: Spark's / returns a decimal (2 / 3 is 0.667), but PostgreSQL and SQL Server return 0 for 2 / 3. Multiplying by 100.0 or casting first makes the query safe everywhere. Second, dividing by zero: with ANSI mode off (Spark 3, and this site's engine) it gives NULL; with ANSI mode on, the default from Spark 4.0, it raises an error. x / nullif(y, 0) returns NULL in both.

Common mistakes

  • COUNT with ELSE 0 — COUNT counts zeros, because 0 is not NULL. Use sum(CASE ... THEN 1 ELSE 0 END) or count_if.
  • Several queries for several counts — Running one query per status scans the table again each time. One GROUP BY with conditional aggregates scans it once.
  • Integer division in rates — In PostgreSQL or SQL Server, 2 / 3 is 0. Write 100.0 * a / b or cast to decimal first.
  • Forgetting the NULL bucket — Conditions like status = 'x' never match NULL. Add an IS NULL column, or the columns will not add up to the total.

Key takeaways

  • Conditional aggregates filter inside the aggregate, so one GROUP BY can produce many counts.
  • CASE inside SUM works everywhere; FILTER and count_if are shorter where supported.
  • COUNT counts non-NULL values: never pair it with ELSE 0.
  • For rates, guard against integer division and divide-by-zero with 100.0 * and nullif.

Interview prep

THE QUESTION

"In one query, show for each restaurant its total orders, delivered orders and the share of orders that were delivered."

SELECT restaurant, count(*) AS orders, sum(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered, 100.0 * sum(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) / count(*) AS delivered_pct FROM orders GROUP BY restaurant. CASE inside SUM works in every engine (mention FILTER and count_if as shorter forms), 100.0 avoids integer division, and count(*) can never be 0 inside a group, so no NULLIF is needed here.

Avoid: "I would run one query per status and combine the results." It works, but scans the table once per number, and the counts can come from different moments if data is arriving.

Follow-ups · answer out loud, then open

Follow-up"How would you count distinct customers who placed at least one cancelled order, per restaurant, in the same GROUP BY?"
count(DISTINCT CASE WHEN status = 'cancelled' THEN customer_id END): the CASE has no ELSE, so other rows become NULL, which COUNT(DISTINCT) skips. In Spark you can also write count(DISTINCT customer_id) FILTER (WHERE status = 'cancelled').
Scenario"A dashboard's unique-users tile over 3 billion events is slow. The number does not need to be exact. What do you change?"
Replace COUNT(DISTINCT user_id) with approx_count_distinct(user_id), a HyperLogLog++ sketch that uses a few kilobytes per group; its relative error is about 5% by default and can be set lower with a second argument. For repeated rollups, store the sketches per day and merge them instead of recounting raw events.
Trap"avg(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) and avg(CASE WHEN status = 'delivered' THEN 1 END) return the same delivered rate."
No. The first averages a 1 or a 0 over every row, which is the delivered share. The second has NULL instead of 0, so AVG skips the non-delivered rows and returns 1 for every group with a delivered order.

Check yourself

4 questions

What does count(CASE WHEN ok THEN 1 ELSE 0 END) return for 10 rows, 3 of them ok?

Show the answer

10. COUNT counts the zeros too, because 0 is not NULL.

A restaurant had 3 orders from 2 customers. What is count(DISTINCT customer_id)?

Show the answer

2. Each customer is counted once.

In PostgreSQL, what is 2 / 3 for two integers?

Show the answer

0. Integer division truncates; Spark would return 0.667.

Which expression avoids a divide-by-zero error in every engine?

Show the answer

a / nullif(b, 0). nullif turns a zero divisor into NULL, and dividing by NULL gives NULL.

Practise this

Problems that use this, graded on hidden tests

See all 4 problems →

Keep going

Up next · new module: Joining tables · 7 min read
Inner and outer joins
Match rows across tables with INNER, LEFT, RIGHT and FULL joins, and see exactly which rows each one keeps.

Related lessons

Previous: GROUP BY and HAVING

Primary sources: Aggregate functions · GROUP BY clause (FILTER)