Sub topic 10
Counting and summing with outer joins
This chapter covers aggregation over outer joins. It assumes you can write SELECT, WHERE and GROUP BY, understand NULL, and know the LEFT JOIN syntax from the earlier chapters. All examples use the same customers and orders tables as the rest of the tutorial.
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT REFERENCES customers (customer_id),
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total) VALUES
(101, 1, 50.00),
(102, 1, 20.00),
(103, 2, 35.00),
(104, NULL, 15.00);Why aggregation and outer joins interact
A LEFT JOIN returns one row per match, plus one NULL-padded row for every left row with no match. Aggregate functions then run over those rows. Two facts decide whether your numbers are right:
- Most aggregates skip
NULLvalues.COUNT(column),SUM,AVG,MINandMAXignore them. COUNT(*)counts rows, not values. A NULL-padded row is still a row.
A customer with no orders appears as a single row whose order columns are all NULL. If you count that row, you report one order where there are none. If you sum those columns, you get NULL instead of zero.
Counting: choose the column carefully
Here is the join before any grouping:
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- Cleo NULL NULLCleo's row exists only because the join preserved her. Now compare two ways of counting:
SELECT c.name,
COUNT(*) AS wrong_count,
COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;
-- Ada 2 2
-- Ben 1 1
-- Cleo 1 0COUNT(*) gives Cleo a count of 1 because it counts the padded row. COUNT(o.order_id) gives 0 because order_id is NULL in that row and COUNT(column) skips NULL.
Count a column from the right table that cannot be NULL in a real match, normally its primary key. Counting a nullable column undercounts. For example, COUNT(o.customer_id) would work here only because every matched row has a customer ID, which is true by construction of the join condition, but the primary key is the safer habit.
Summing: turning NULL into zero
SUM over a group in which every value is NULL returns NULL, not 0. Cleo's group contains only the padded row, so her sum is NULL. Wrap the aggregate in COALESCE to supply a default:
SELECT c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total), 0) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;
-- Ada 2 70.00
-- Ben 1 35.00
-- Cleo 0 0Put COALESCE outside the aggregate. SUM(COALESCE(o.total, 0)) also works for this table, but it changes values before summing and does nothing about the case where the whole group is empty of real rows in other aggregates such as MAX. Wrapping the result is simpler and applies the same way to SUM, MAX and MIN.
AVG needs a decision rather than a default. AVG(o.total) for Cleo is NULL, which honestly says "no average exists". Replacing it with 0 would claim her average order is zero. Use COALESCE only when the zero is a true value for your report, as it is for a count or a total.
| Expression | Result for Cleo | Why |
|---|---|---|
| `COUNT(*)` | 1 | Counts the padded row |
| `COUNT(o.order_id)` | 0 | Skips `NULL` |
| `SUM(o.total)` | `NULL` | No non-NULL values |
| `COALESCE(SUM(o.total), 0)` | 0 | Default applied after summing |
| `AVG(o.total)` | `NULL` | No values to average |
Group by the key, not only the label
The examples group by c.customer_id, c.name. Grouping by c.name alone would merge two different customers who share a name into one row. Grouping by the primary key keeps them apart. Include the name as well, because standard SQL requires every non-aggregated selected column to appear in GROUP BY. Some databases, such as PostgreSQL and MySQL in default modes, allow you to list only the primary key when other columns are functionally dependent on it, but the version that lists both works everywhere.
Filters that break the aggregate
The ON-versus-WHERE rule from the previous chapter matters even more here. Suppose you want each customer's count of orders over 30:
-- Wrong: the WHERE removes Cleo's padded row, and Ada loses her small order
SELECT c.name, COUNT(o.order_id) AS big_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30
GROUP BY c.customer_id, c.name;
-- Ada 1
-- Ben 1Cleo disappears from the result, because her padded row has o.total as NULL and NULL > 30 is not true. The query has become an inner join. Move the condition into ON:
SELECT c.name, COUNT(o.order_id) AS big_orders
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 30
GROUP BY c.customer_id, c.name;
-- Ada 1
-- Ben 1
-- Cleo 0Now every customer is kept, and the condition only decides which orders count as matches. Conditions on the preserved (left) table, such as WHERE c.name <> 'Ben', are safe in WHERE because they remove whole customers on purpose.
Row multiplication inflates sums
A one-to-many join repeats the left row once per match. That is correct for listing, but it breaks sums of left-side columns. Suppose customers had a credit_limit column, and you wanted the total credit limit across customers:
SELECT SUM(c.credit_limit)
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;Ada has two orders, so her limit is added twice. The result overstates the total. The same problem appears when you join two one-to-many tables to the same parent, for instance orders and payments. Every order pairs with every payment for that customer, so both counts and sums inflate.
There are two reliable fixes:
- Aggregate each many-side table in a subquery first, then join the one-row-per-customer results.
- Count distinct keys, for example
COUNT(DISTINCT o.order_id), which protects counts but does not protect sums.
The first fix is the general one:
SELECT c.name,
COALESCE(s.order_count, 0) AS order_count,
COALESCE(s.total_spent, 0) AS total_spent
FROM customers c
LEFT JOIN (
SELECT customer_id,
COUNT(*) AS order_count,
SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
) s ON s.customer_id = c.customer_id;
-- Ada 2 70.00
-- Ben 1 35.00
-- Cleo 0 0Here the subquery produces at most one row per customer, so the join cannot multiply anything. Cleo has no row in s, so her columns are NULL and COALESCE converts them. Note that the COALESCE moves to the outer query, because the subquery has no row for her to default. Order 104 has a NULL customer_id, so it forms its own group in the subquery, and that group finds no match in customers. It does not appear in the final result.
Diagram: where each step happens
The order in which the database processes the query explains every result above.
A WHERE condition on the right table acts at step C, after the padded rows exist, and removes them. An ON condition acts at step A and only changes what counts as a match.
Common errors
- Using
COUNT(*)with aLEFT JOIN. Customers with no match report 1 instead of 0. Count a right-table key. - Forgetting
COALESCEaroundSUM. The report showsNULLor a blank where a zero belongs, and later arithmetic such astotal - discountreturnsNULL. - Right-table filter in
WHERE. The outer join silently becomes an inner join and unmatched customers vanish. - Joining two one-to-many tables, then summing. Totals are multiplied. Pre-aggregate each table.
- Using
HAVINGto find zero counts, then filtering in the wrong place.HAVING COUNT(o.order_id) = 0works for finding customers with no orders, but aWHERE o.order_id IS NULLanti-join is usually cheaper because it filters before grouping.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(o.order_id) = 0;
-- CleoExercise
Using the sample data, write a query that returns every customer's name, their number of orders worth at least 30, and the sum of those orders (0 if none). What does Ada's row look like, and why is Cleo still listed?
Show answer
SELECT c.name, COUNT(o.orderid) AS bigorders, COALESCE(SUM(o.total), 0) AS bigtotal FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid AND o.total >= 30 GROUP BY c.customerid, c.name; Ada gets 1 and 50.00 (order 101 only, because order 102 for 20.00 fails the condition in ON and is not a match). Ben gets 1 and 35.00. Cleo is still listed with 0 and 0 because the condition is in ON, so her unmatched row is preserved and COUNT of a NULL order_id is 0. Putting the condition in WHERE would remove Cleo.
Exercise
A query joins customers to orders and to a payments table (many payments per customer), then runs SUM(o.total) grouped by customer. Ada has 2 orders and 3 payments. Roughly how many times is each of Ada's order totals counted, and how do you fix it?
Show answer
Each order pairs with every payment, so each order total is counted 3 times and the sum is three times too large. Fix it by aggregating orders and payments separately in subqueries grouped by customer_id, then LEFT JOINing both one-row-per-customer results to customers and wrapping the results in COALESCE.