SQL COUNT() Function โ Count Records in Your Tables
Introduction โ What is SQL COUNT()?
The COUNT() function in SQL is used to count the number of rows returned by a query. It is one of the most commonly used aggregate functions and works with both numeric and non-numeric data.
In this guide, you’ll learn how to:
- Use
COUNT()to count all rows or non-NULL values - Count rows by group using
GROUP BY - Filter results with
HAVING - Understand the difference between
COUNT(*),COUNT(column), andCOUNT(DISTINCT column)
1. Basic COUNT() Syntax
SELECT COUNT(*) FROM table_name;
Counts all rows, including those with NULLs.
2. COUNT(column) โ Excludes NULLs
SELECT COUNT(email) FROM users;
Counts only rows where email is not NULL.
3. COUNT(*) vs COUNT(column)
| Function | Description |
|---|---|
COUNT(*) | Counts all rows, including NULLs |
COUNT(column) | Counts only non-NULL values in the column |
4. COUNT(DISTINCT column)
SELECT COUNT(DISTINCT department) FROM employees;
Counts unique departments only.
5. COUNT() with GROUP BY
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
Counts the number of employees per department.
6. Filtering Counts with HAVING
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
Shows only departments with more than 10 employees.
Best Practices
| Recommended | Avoid This |
|---|---|
| Use aliases for readable output | Leaving COUNT() column unnamed |
Use COUNT(*) when counting all rows | Using COUNT(column) if NULLs exist |
Use DISTINCT carefully with COUNT | Assuming COUNT() handles uniqueness by default |
Summary โ Recap & Next Steps
The COUNT() function is fundamental for SQL querying. It helps determine how many records exist, either in total or under certain conditions.
Key Takeaways:
COUNT(*)counts all rowsCOUNT(column)ignores NULLsCOUNT(DISTINCT col)counts unique values- Combine with
GROUP BYfor grouped insights
Real-World Relevance:
Used in reporting totals, dashboard KPIs, inventory counts, user activity tracking, and analytics.
Next: Explore CASE WHEN for conditional aggregation.
FAQ โ SQL COUNT Function
What does COUNT(*) count?
It includes all rows, even if columns have NULLs.
When should I use COUNT(column)?
When you want to count only rows where that column has a value (non-NULL).
Can I count distinct values?
Yes, use COUNT(DISTINCT column_name).
What is the difference between COUNT(*) and COUNT(1)?
Functionally the same, but COUNT(*) is more readable and standard.
Can I use COUNT() with JOINs?
Absolutely. You can count joined rows or group counts per relationship.
Share Now :
