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

Part 04 / Topic 3 of 6

GROUP BY

GROUP BY splits rows into groups and runs the aggregates once per group — one output row each. Orders by status:

SELECT status, count(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;
  status   | orders 
-----------+--------
 delivered |      6
 cancelled |      1
 pending   |      1
 shipped   |      1
(4 rows)

Stock and shelf value per category:

SELECT category_id,
       count(*)           AS products,
       sum(stock)         AS units,
       sum(price * stock) AS shelf_value
FROM products
GROUP BY category_id
ORDER BY shelf_value DESC;
 category_id | products | units | shelf_value 
-------------+----------+-------+-------------
           5 |        2 |    65 |    35935.00
           4 |        2 |    23 |    25600.00
           2 |        2 |   160 |     6800.00
           1 |        1 |   200 |     3000.00
           6 |        2 |    30 |     2400.00
           3 |        1 |    12 |      540.00
(6 rows)

The GROUP BY rule: once you group, SELECT may only mention (a) the grouping columns and (b) aggregates of anything else. Postgres enforces it:

SELECT status, order_date, count(*) FROM orders GROUP BY status;
ERROR:  column "orders.order_date" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT status, order_date, count(*) FROM orders GROUP BY sta...
                       ^

The error is the database asking a fair question: each delivered group holds several different order_dates — which one should it print? Either group by order_date too, or aggregate it (max(order_date) — "latest order per status").

Grouping by an expression works, and is how reports fall into months (date_trunc from Part 3 pays off):

SELECT date_trunc('month', order_date)::date AS month,
       count(*) AS orders
FROM orders
GROUP BY date_trunc('month', order_date)
ORDER BY month;
   month    | orders 
------------+--------
 2025-01-01 |      2
 2025-02-01 |      2
 2025-03-01 |      3
 2025-04-01 |      2
(4 rows)

🧪 Quick quiz — answer from memory, then check.

  1. After GROUP BY status, may SELECT include plain order_date? Why not?
  2. How many output rows does GROUP BY produce?
Show the answers
  1. No — the group holds many order_dates and Postgres won't pick one for you. Group by it too, or aggregate it.
  2. One per distinct group (plus none for groups that don't exist — no rows, no group).

Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.

Search the guide