COUNT
Count rows or non-NULL values in a grouped or ungrouped result set.
Syntax
COUNT(column_name)
COUNT(*)What it does
COUNT(*) counts all rows, including those with NULL values. COUNT(column_name) counts only rows where the expression is not NULL.
Example
SELECT
customer_id,
COUNT(*) AS total_orders,
COUNT(cancelled_at) AS cancelled_orders
FROM orders
GROUP BY customer_id;Common gotchas
COUNT(*)is different fromCOUNT(column)when the column can beNULL- a filter in the
WHEREclause changes which rows are counted - a
LEFT JOINwithCOUNT(*)can be misleading unless you are counting the joined rows intentionally
Safety checklist
- decide whether
NULLs should count or be excluded - confirm the correct grain before grouping
- check whether the join semantics are producing the row set you expect