← All posts
postMay 31, 2026
SQL: COUNT vs COUNT DISTINCT
#sql#count#aggregations
sql
-- Wrong: counts orders, not users
SELECT COUNT(*) AS active_users
FROM orders
WHERE created_at >= '2026-05-01';
-- Right: counts unique users
SELECT COUNT(DISTINCT user_id) AS active_users
FROM orders
WHERE created_at >= '2026-05-01';COUNT(*) counts every row, including duplicates. COUNT(DISTINCT column) counts only unique values of that column. The difference matters enormously when reporting business metrics.
A classic example: how many users placed an order this month? COUNT(*) on the orders table counts orders, not users. COUNT(DISTINCT user_id) counts users. Confusing the two is one of the most common SQL mistakes that produces wrong dashboards.