SQL: INNER JOIN vs LEFT JOIN when counting orders per customer

Backend Live Coding November 13, 2026 sql

With INNER JOIN, customers without orders are lost.

sql
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
-- ======================================================================
-- Q: INNER JOIN vs LEFT JOIN: list customers and their number of orders,
-- including those with none.
--
-- With INNER JOIN, customers without orders are lost. Use COUNT(o.id) and not
-- COUNT(*), because COUNT(*) also counts the row with NULL as 1.
-- ======================================================================

SELECT c.id, c.name, COUNT(o.id) AS orders
FROM customer c
LEFT JOIN "order" o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY orders DESC;