Sub topic 3
Grouping and aggregating joined data
This chapter assumes you know SELECT, WHERE, GROUP BY, primary keys, foreign keys, and INNER JOIN with an ON condition. The examples use the customers and orders tables from the earlier chapters.
Grouping and aggregating joined data
Group joined rows by a key, then aggregate each group. Customers with no matching orders form no group, so they do not appear.
SELECT c.name, COUNT(*) AS order_count, SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;If a join adds child rows, a parent column summed after the join is counted once per child. Aggregate the child table first, then join the result to the parent.
Joining a table to itself
A self join uses two aliases so one table plays two roles. Employees whose manager_id is NULL have no match and are excluded.
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
INNER JOIN employees AS m ON m.id = e.manager_id;Joins on ranges and inequalities
An ON condition can use any comparison, not only equality. This example assumes a discounttiers table with mintotal, max_total and label columns.
SELECT o.id, o.total, t.label
FROM orders AS o
INNER JOIN discount_tiers AS t
ON o.total >= t.min_total
AND o.total < t.max_total;Range joins often cannot use a simple equality index lookup, so check their execution plans.
USING and NATURAL JOIN shorthand
USING (column) joins on a column that has the same name in both tables. NATURAL JOIN joins on every column name the two tables share. A column added later can silently change a NATURAL JOIN, so write an explicit ON in production code.
Reading older comma-style joins
FROM customers AS c, orders AS o WHERE o.customer_id = c.id returns the same rows as the INNER JOIN form. If the WHERE condition is missing, the database returns every combination of rows. Prefer explicit INNER JOIN in new code.
When an inner join is not enough: outer joins
An inner join drops unmatched rows. A LEFT JOIN keeps every row from the left table. COUNT(o.id) counts only non-NULL order ids, so customers without orders get 0.
SELECT c.name, COUNT(o.id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;Join performance: indexes and execution plans
Join columns such as orders.customer_id should have an index. In PostgreSQL, EXPLAIN shows the plan:
EXPLAIN
SELECT c.name, o.id
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id;An Index Scan on orders means the join uses the index. A Seq Scan on a large table suggests a missing index. Small tables often use sequential scans, and plan output varies by database.
Common mistakes and how to debug a join
- Omitting the ON condition, which creates a cartesian product.
- Joining on the wrong column.
- Summing a parent column after a one-to-many join.
- Filtering the outer side of a LEFT JOIN in WHERE.
To debug, run each join step alone and compare row counts.
Exercise
List every customer with their total spend, including customers with no orders. Which function avoids counting an unmatched row as an order?
Show answer
Use a LEFT JOIN from customers to orders, group by c.id and c.name, and select COALESCE(SUM(o.total), 0) AS spend. COUNT(o.id) counts only non-NULL order ids, so an unmatched customer gets 0 instead of 1.