COUNT — How Many?
COUNT(*) counts rows, COUNT(column) counts non-NULL values and COUNT(DISTINCT column) counts different values, returning 0 when nothing matches.
Compare counting rows, non-NULL values and distinct values on the same data.
"How many customers do we have?" "How many orders shipped this week?" "How many customers never gave us an email?" Counting is the first question almost every report asks. SQL answers all three with COUNT — but in three slightly different forms, and mixing them up gives believable wrong numbers.
The rule
COUNT(*) counts rows; COUNT(column) counts values that are not NULL.
COUNT is an aggregate function: it takes many rows in and gives one number out. Our customers table:
| customer_id | name | city | |
|---|---|---|---|
| 1 | Asha | Pune | asha@example.com |
| 2 | Ravi | Delhi | NULL |
| 3 | Meera | Pune | meera@example.com |
| 4 | Kabir | Mumbai | kabir@example.com |
SELECT COUNT(*) FROM customers; -- 4: every row
SELECT COUNT(email) FROM customers; -- 3: Ravi's NULL is skipped
SELECT COUNT(DISTINCT city) FROM customers; -- 3: Pune, Delhi, MumbaiCOUNT(*)counts rows, whatever they contain.COUNT(column)counts rows where that column is not NULL.COUNT(DISTINCT column)counts the different non-NULL values.
WHERE runs before COUNT, so it narrows the rows first: SELECT COUNT(*) FROM customers WHERE city = 'Pune'; gives 2. And when no rows match at all, COUNT returns 0, not NULL — it is the one aggregate that always gives a number.