SQL COUNT function

Here’s a clean and practical guide to the SQL COUNT function, including behavior with NULLs, best practices, and real-world examples.


 What SQL COUNT function Does

COUNT() returns the number of rows that match a condition.


 Types of COUNT

1. COUNT(*) — Count all rows

Counts every row, including those with NULL values.


2. COUNT(column) — Count non-NULL values

Ignores NULLs in the specified column.


If email is NULL for some users, those rows are not counted.


3. COUNT(DISTINCT column) — Count unique non-NULL values

Useful for determining how many unique values exist.


 COUNT with WHERE (filter first)


COUNT with GROUP BY (per category)



 Important Behavior Notes

COUNT(*) counts all rows
COUNT(column) ignores NULLs
COUNT(DISTINCT ...) ignores NULLs and removes duplicates
✔ Use COUNT with GROUP BY for per-group counts
✔ Use WHERE to filter before counting


 Real-World Examples

Number of completed orders


Count users by signup month


 

You may also like...