LEFT JOIN COUNT(*) returns 1 instead of 0: why, and the fix
COUNT(*) counts rows, and a LEFT JOIN returns at least one row for every row of the left table, even when nothing matches on the right. A group with no matches still has that one row, so COUNT(*) says 1. To get 0, count a column from the right-hand table instead of *.
How it usually happens
Someone asks for a list of customers with the number of orders each one placed, including the people who never bought anything. You know that means a LEFT JOIN, so you write one. The query runs with no error. Then you notice Dev, who has never ordered, sitting there with 1. Nothing looks broken, and that is why this one ends up in real reports.
The tables
| id | name |
|---|---|
| 1 | Ana |
| 2 | Ben |
| 3 | Chloe |
| 4 | Dev |
| order_id | customer_id | amount |
|---|---|---|
| 101 | 1 | 50 |
| 102 | 1 | 30 |
| 103 | 2 | 20 |
| 104 | 3 | 75 |
Dev has no orders.
The query that returns 1
SELECT c.name, COUNT(*) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY c.name;
| name | order_count |
|---|---|
| Ana | 2 |
| Ben | 1 |
| Chloe | 1 |
| Dev | 1 |
Dev shows 1 order and has none.
What the join returns before the count
| name | order_id |
|---|---|
| Ana | 101 |
| Ana | 102 |
| Ben | 103 |
| Chloe | 104 |
| Dev | NULL |
The LEFT JOIN keeps Dev and fills the order columns with NULL. That is still one row, and COUNT(*) counts it.
The fix
SELECT c.name, COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY c.name;
| name | order_count |
|---|---|
| Ana | 2 |
| Ben | 1 |
| Chloe | 1 |
| Dev | 0 |
COUNT with a column name skips NULLs. Dev's order_id is NULL, so the count is 0.
Rule to remember: after a LEFT JOIN, count a column from the right-hand table, ideally its primary key.
Try it yourself
Same trap, different tables. A company has four departments, and Legal has nobody in it yet.
| id | name |
|---|---|
| 1 | Sales |
| 2 | Support |
| 3 | Design |
| 4 | Legal |
| id | name | department_id |
|---|---|---|
| 1 | Maya | 1 |
| 2 | Omar | 1 |
| 3 | Lena | 2 |
| 4 | Raj | 3 |
| 5 | Ines | 1 |
The query below is meant to list every department with the number of people in it, as department and headcount, sorted by department. It gives Legal a headcount of 1. Fix it so Legal shows 0.
Hint
Which table does the thing you are counting live in?
Show solution
SELECT d.name AS department, COUNT(e.id) AS headcount
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.name
ORDER BY d.name;| department | headcount |
|---|---|
| Design | 1 |
| Legal | 0 |
| Sales | 3 |
| Support | 1 |
MintQuery has 500+ exercises like this one, in lessons of a few minutes.
Start freeGet the app