In two sentences
Conditional aggregation computes several numbers over the same group in one pass: each aggregate only looks at the rows that meet its own condition. It's how you count paid and refunded orders side by side, compute a rate, or turn rows into columns (a pivot).
See it
The same orders as in GROUP BY and aggregation, now one row per day with a column per status:
| day | orders | refunded | paid revenue | refund rate |
|---|---|---|---|---|
| 04-01 | 3 | 0 | 140 | 0.0 |
| 04-02 | 2 | 1 | 30 | 0.5 |
One GROUP BY day, four aggregates, each with its own filter.
In SQL
SELECT
CAST(order_ts AS date) AS day,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded,
sum(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue,
count_if(status = 'refunded') * 1.0 / count(*) AS refund_rate
FROM orders
GROUP BY CAST(order_ts AS date);Three ways to write a condition, all valid in Trino: FILTER (WHERE …) after any aggregate, a CASE inside it,
and count_if(…).
Pivot (rows to columns): one filtered aggregate per column.
SELECT product,
sum(amount) FILTER (WHERE quarter = 1) AS q1,
sum(amount) FILTER (WHERE quarter = 2) AS q2,
sum(amount) FILTER (WHERE quarter = 3) AS q3
FROM sales
GROUP BY product;A product with no sales in a quarter gets NULL there, not 0.
Unpivot (columns to rows): Trino has no UNPIVOT; unnest two parallel arrays.
SELECT product, quarter, amount
FROM wide
CROSS JOIN UNNEST(ARRAY['q1', 'q2'], ARRAY[q1, q2]) AS t(quarter, amount);Common mistakes
- Integer division.
count_if(status = 'refunded') / count(*)is integer division in Trino: 1 / 2 is 0. Multiply by1.0first (or cast todouble). - Filtering in
WHEREinstead.WHERE status = 'refunded'removes the other rows before grouping, socount(*)no longer counts all orders, and days without a refund disappear. CASEwithoutELSE. Non-matching rows become NULL.countandsumignore them, but a group where nothing matches sums to NULL instead of 0.- Overlapping
WHENs.CASEstops at the first true condition. Put the most specific first. - Hard-coding the pivot's columns and forgetting new values. A fourth quarter, a new status: the pivot silently drops them. Check the distinct values before writing the columns.
What an interviewer asks next
- "Conversion rate per variant in an A/B test?"
count_if(converted) * 1.0 / count(*)grouped by variant, and check that every user appears once (see Deduplication). - "Why not one query per status?" One scan instead of several, and the numbers come from exactly the same rows.
Go further
Modern SQL's page on FILTER shows which databases support it and how to emulate it with CASE elsewhere.
Practise it
Pivot Quarterly Sales into a Report Layout, then Friend Request Acceptance Rate Within 7 Days, then A/B Test Readout with Clean Exposure Data.