Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 04 / Stage 1

Summarising data

Goal: Turn many rows into answers — totals, averages and counts, grouped the way the business thinks, filtered the right way at the right stage. Time: ~1.5 hours

What you will learn

  • The aggregate functions: count, sum, avg, min, max — and how they treat NULL
  • count(*) vs count(col) vs count(DISTINCT col): three different questions
  • GROUP BY: one row per group, and the rule about what SELECT may mention
  • HAVING: filtering groups, and how it differs from WHERE
  • The FILTER clause: several conditional counts in one pass
  • string_agg and array_agg: collapsing values into lists

Still one table at a time — joins arrive in Stage 2. Everything runs on shopdb.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Try each one yourself first, in psql against shopdb. Then check the solution.


Exercise 1: The orders dashboard line

What to do: One query: how many orders exist, the date of the first, and the date of the latest.

Sample output:

 orders | first_order | latest_order 
--------+-------------+--------------
      9 | 2025-01-10  | 2025-04-20
(1 row)

💡 Hint: count(*), min, max — dates aggregate as naturally as numbers.


Show the solution to Exercise 1
-- Exercise 1: The orders dashboard line
SELECT count(*)        AS orders,
       min(order_date) AS first_order,
       max(order_date) AS latest_order
FROM orders;

Exercise 2: Three counts, one column

What to do: On products.supplier_id, show all three counts — rows, non-NULL values, distinct values — and before running, predict each number. (Remember the Desk Lamp.)

Sample output:

 all_products | with_supplier | distinct_suppliers 
--------------+---------------+--------------------
           10 |             9 |                  3
(1 row)

💡 Hint: the lamp has no supplier; three suppliers serve several products each.


Show the solution to Exercise 2
-- Exercise 2: Three counts, one column
-- Desk Lamp has no supplier, and three suppliers serve several products each.
SELECT count(*)                    AS all_products,
       count(supplier_id)          AS with_supplier,
       count(DISTINCT supplier_id) AS distinct_suppliers
FROM products;

Exercise 3: What actually sells

What to do: From order_items alone, show units sold and revenue (quantity × unit price) per product, biggest earner first. One product never sold — should it appear? Why not?

Sample output:

 product_id | units_sold | revenue 
------------+------------+---------
          1 |          2 | 2400.00
          4 |          3 | 1197.00
          2 |          1 |  950.00
          3 |          1 |  799.00
          5 |          5 |  175.00
          6 |          3 |  165.00
          8 |          1 |  120.00
          7 |          1 |   80.00
          9 |          1 |   45.00
(9 rows)

💡 Hint: GROUP BY product_id — product 10 has no order_items rows, and no rows means no group. (Showing it with a 0 needs a join — Stage 2's very first lesson.)


Show the solution to Exercise 3
-- Exercise 3: What actually sells
SELECT product_id,
       sum(quantity)              AS units_sold,
       sum(quantity * unit_price) AS revenue
FROM order_items
GROUP BY product_id
ORDER BY revenue DESC;

Exercise 4: Orders by month

What to do: Count orders per calendar month, in month order, with the month shown as a date.

Sample output:

   month    | orders 
------------+--------
 2025-01-01 |      2
 2025-02-01 |      2
 2025-03-01 |      3
 2025-04-01 |      2
(4 rows)

💡 Hint: group by date_trunc('month', order_date); cast to date for display.


Show the solution to Exercise 4
-- Exercise 4: Orders by month
SELECT date_trunc('month', order_date)::date AS month,
       count(*) AS orders
FROM orders
GROUP BY date_trunc('month', order_date)
ORDER BY month;

Exercise 5: Repeat sellers

What to do: Which products appear in more than one order? Show product_id and how many orders it appears in.

Sample output:

 product_id | times_ordered 
------------+---------------
          1 |             2
          4 |             2
          5 |             2
          6 |             2
(4 rows)

💡 Hint: the condition tests an aggregate, so it lives in HAVING.


Show the solution to Exercise 5
-- Exercise 5: Repeat sellers
SELECT product_id, count(*) AS times_ordered
FROM order_items
GROUP BY product_id
HAVING count(*) > 1
ORDER BY times_ordered DESC, product_id;

Exercise 6: The order status summary

Scenario: The weekly ops email needs the status breakdown. What to do: Two queries. First: each status with its order count and percentage of all orders, biggest first. (For the total, a (SELECT count(*) FROM orders) in the division works — a scalar subquery, formally Stage 2, useful today.) Second: one row with total, delivered and cancelled side by side using FILTER.

Sample output:

  status   | orders | pct  
-----------+--------+------
 delivered |      6 | 66.7
 cancelled |      1 | 11.1
 pending   |      1 | 11.1
 shipped   |      1 | 11.1
(4 rows)

 total_orders | delivered | cancelled 
--------------+-----------+-----------
            9 |         6 |         1
(1 row)

💡 Hint: round(100.0 * count(*) / (SELECT count(*) FROM orders), 1), then count(*) FILTER (WHERE ...) twice.


Show the solution to Exercise 6
-- Exercise 6: The order status summary (the part's mini-project)
-- Percentages via the Part 3 pattern. The (SELECT count(*) FROM orders)
-- is a scalar subquery — one query used as a single value. Stage 2 covers
-- them properly; consider this your preview.
SELECT status,
       count(*)                                   AS orders,
       round(100.0 * count(*) /
             (SELECT count(*) FROM orders), 1)    AS pct
FROM orders
GROUP BY status
ORDER BY orders DESC;

SELECT count(*)                                     AS total_orders,
       count(*) FILTER (WHERE status = 'delivered') AS delivered,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders;

Exercise 7: Orders per status, listed

What to do: One row per status with its order ids in a comma list, in id order. (order_id is a number — string_agg wants text.)

Sample output:

  status   |    order_ids     
-----------+------------------
 cancelled | 5
 delivered | 1, 2, 3, 6, 8, 9
 pending   | 7
 shipped   | 4
(4 rows)

💡 Hint: string_agg(order_id::text, ', ' ORDER BY order_id).

Show the solution to Exercise 7
-- Exercise 7: Orders per status, listed
SELECT status,
       string_agg(order_id::text, ', ' ORDER BY order_id) AS order_ids
FROM orders
GROUP BY status
ORDER BY status;

Common mistakes

Mistake What happens Fix
Non-grouped column in SELECT must appear in the GROUP BY clause... Group by it, or aggregate it
Testing aggregates in WHERE aggregate functions are not allowed in WHERE HAVING
Expecting sum of no rows to be 0 NULL COALESCE(sum(x), 0)
count(col) when you meant rows NULLs silently missing from the count count(*)
Averaging a column with NULLs unknowingly Average of the known values only Decide: is that right? If not, avg(COALESCE(x, 0))
Row conditions in HAVING Works but groups junk it could have discarded Move the condition to WHERE

Quick recap

  • Aggregates collapse many rows to one: count, sum, avg, min, max — all skip NULLs; sum of nothing is NULL.
  • count(*) counts rows, count(col) counts non-NULL values, and count(DISTINCT col) counts different values.
  • GROUP BY runs the aggregates once per group; the SELECT list may hold only group columns and aggregates.
  • WHERE filters rows before grouping, HAVING filters groups after, FILTER narrows one aggregate.
  • string_agg / array_agg summarise into lists, with their own inner ORDER BY.

Checklist

Before the Stage 1 project, make sure you can:

  • Explain the three counts, and when each gives a different number.
  • Group orders by month and products by category without a GROUP BY error.
  • Put a condition in WHERE vs HAVING correctly, first try.
  • Produce delivered / cancelled / total in one query with FILTER.
  • Collapse a group's names into an ordered comma list.

Read more: the official aggregate functions reference and the GROUP BY and HAVING sections of the queries chapter.

Search the guide