๐ข 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 :
