TheAnalyst / SQLAll lessons ↗
Day 21 · Advanced SQL · 10–20 minutes

Conditional aggregation

Use CASE inside SUM or COUNT to compute multiple metrics in one pass.

01 · Learn

The idea

Use CASE inside SUM or COUNT to compute multiple metrics in one pass. Read the query line by line and identify the input table, the transformation, and the shape of the result before running it.

SELECT SUM(CASE WHEN amount >= 2000 THEN 1 ELSE 0 END) AS large_orders, COUNT(*) AS all_orders FROM orders;
Read it actively

Before running the example, predict the output columns and whether the query returns one row, many rows, or possibly no rows.

02 · Recall

Explain it without looking

In your own words, explain the main SQL feature in today’s lesson and why it answers the question.

03 · Solve

Run your own query

Count large orders (amount at least 2000) and all orders in one query.

Loading browser SQL engine…
04 · Repeat

Close the loop