MintQueryStart free
← All guides

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

customers
idname
1Ana
2Ben
3Chloe
4Dev
orders
order_idcustomer_idamount
101150
102130
103220
104375

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;
nameorder_count
Ana2
Ben1
Chloe1
Dev1

Dev shows 1 order and has none.

What the join returns before the count

nameorder_id
Ana101
Ana102
Ben103
Chloe104
DevNULL

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;
nameorder_count
Ana2
Ben1
Chloe1
Dev0

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.

departments
idname
1Sales
2Support
3Design
4Legal
employees
idnamedepartment_id
1Maya1
2Omar1
3Lena2
4Raj3
5Ines1

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;
departmentheadcount
Design1
Legal0
Sales3
Support1

MintQuery has 500+ exercises like this one, in lessons of a few minutes.

Start freeGet the app