runtime
15 / 88

lesson 15 Calculations & data quality · intermediate

Conditional aggregation

Calculate several conditional metrics in one summary.

the idea

Put CASE inside SUM to count or add only matching rows. ELSE 0 prevents nonmatching rows from contributing. This can produce multiple summaries in one scan.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_count
FROM orders;

Watch for: COUNT(CASE ... ELSE 0 END) counts zero values too because they are not NULL.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. See paid vs other statuses. Orders mix paid and unpaid statuses. Conditional aggregation can count only the paid ones in one pass.

    step-1.sql
    SELECT id, status, quantity
    FROM orders
    ORDER BY id;
  2. Count only paid rows inside SUM. CASE returns 1 for paid rows and 0 otherwise. SUM adds those values into paid_count.

    step-2.sql
    SELECT SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_count
    FROM orders;

challenge 1

Return paid_count: the number of paid orders.

Return paid_countany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.