With INNER JOIN, customers without orders are lost.
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; |