Skip to content

SQL JOIN and GROUP BY, explained with one real question

Answer "how many orders did each store take?" with JOIN and GROUP BY, and learn why a LEFT JOIN, HAVING and count(column) change the answer.

Checked 2026-11-19

The question: how many orders did each store take, busiest first? The orders are in orders, the store names in stores.

JOIN brings the two tables together

SELECT s.name, o.id
FROM orders o
JOIN stores s ON s.id = o.store_id;

JOIN (an inner join) pairs every order with its store, using the condition after ON. An order with no matching store, and a store with no orders, are both left out.

GROUP BY turns rows into one row per group

SELECT s.name, count(*) AS orders
FROM orders o
JOIN stores s ON s.id = o.store_id
GROUP BY s.name
ORDER BY orders DESC;

Every column in the SELECT must either be in the GROUP BY or be inside an aggregate such as count, sum or avg. That rule is why PostgreSQL refuses SELECT s.name, o.status, count(*) ... GROUP BY s.name: which status would it show?

Include the stores with no orders: LEFT JOIN

SELECT s.name, count(o.id) AS orders
FROM stores s
LEFT JOIN orders o ON o.store_id = s.id
GROUP BY s.name;

Two changes matter. LEFT JOIN keeps every store, filling the order columns with NULL where there is none. And count(o.id) counts only non-NULL values, so an empty store shows 0. count(*) would count the one NULL row and show 1.

Filter groups with HAVING, rows with WHERE

SELECT s.name, count(*) AS delivered
FROM orders o
JOIN stores s ON s.id = o.store_id
WHERE o.status = 'delivered'   -- before grouping: which rows count
GROUP BY s.name
HAVING count(*) > 100;         -- after grouping: which groups to show

Try it in your browser

Practise it on a real machineJoins & Aggregation lab
Open the lab