Use COUNT(DISTINCT ...) when joins multiply rows
Protect aggregates from one-to-many duplication.
sqlANYaggregationdistinct
sql
SELECT c.customer_id,
COUNT(DISTINCT 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;Notes
A one-to-many join can inflate counts unless you count distinct entity keys.