← All lessons
Combining and summarizing · Lesson 10 of 10

Reports with CASE

Real reports often want several counts side by side: orders shipped, pending and cancelled, all in one row. Put a CASE inside the aggregate so each row adds 1 only to the count it belongs to. This is called conditional aggregation:

SELECT
  SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
  SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
  SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
Returns
shipped | pending | cancelled
--------+---------+----------
8       | 1       | 1
(1 row)

With GROUP BY you get those columns for each group. This turns what would be rows (one per status) into columns, which is what people mean by a pivot:

SELECT c.name,
  COUNT(*) AS orders,
  SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;
Returns
name | orders | shipped
-----+--------+--------
Ana  | 3      | 3
Ben  | 2      | 2
Cleo | 2      | 1
Dev  | 1      | 1
Eve  | 1      | 0
Finn | 1      | 1
(6 rows)

For a percentage, divide and multiply by 100. Use 100.0 rather than 100 so the division isn't whole-number division (lesson 8 of the first course):

SELECT ROUND(100.0 * SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_shipped
FROM orders;
Returns
pct_shipped
-----------
80
(1 row)

The same trick works with SUM for money: SUM(CASE WHEN p.category = 'Garden' THEN i.qty * p.price ELSE 0 END) adds up just the garden part. Another way to count only some rows is COUNT(CASE WHEN … THEN 1 END): with no ELSE the other rows give NULL, which COUNT skips. PostgreSQL also has COUNT(*) FILTER (WHERE …), which says the same thing more plainly.

That's the end of the second course. You can now combine tables, summarise them by group and build a report in steps. The last course, Advanced SQL, adds window functions, recursive queries, changing data, designing tables and making slow queries fast.

Practice

In one row: how many products cost under 30, and how many cost 30 or more (two columns).

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

SUM(CASE WHEN c THEN 1 ELSE 0 END)Count the rows where c is true.
COUNT(CASE WHEN c THEN 1 END)The same, using COUNT skipping NULLs.
COUNT(*) FILTER (WHERE c)PostgreSQL's plainer way to write it.
pivotTurn values (one row each) into columns.
100.0 * a / bA percentage without whole-number division.

The other AI and data engineering courses