shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

Conditional aggregation and CASE

Beginner · 3 min read

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:

dayordersrefundedpaid revenuerefund rate
04-01301400.0
04-0221300.5

One GROUP BY day, four aggregates, each with its own filter.

Each aggregate only counts the rows that match its condition, so one pass gives a column per status

In SQL

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.

SQL
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.

SQL
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 by 1.0 first (or cast to double).
  • Filtering in WHERE instead. WHERE status = 'refunded' removes the other rows before grouping, so count(*) no longer counts all orders, and days without a refund disappear.
  • CASE without ELSE. Non-matching rows become NULL. count and sum ignore them, but a group where nothing matches sums to NULL instead of 0.
  • Overlapping WHENs. CASE stops 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.