SQL Count
The COUNT function tells you how many rows match a query, and it is the most common way to measure the size of a result set.
Counting rows
COUNT() answers the question 'how many?'. It can count every row in a table, only the rows in a specific column that have a value, or only the distinct values in a column. The exact behavior depends on what you place inside the parentheses.
- COUNT(*) counts every row, including rows that contain NULL values.
- COUNT(column_name) counts only the rows where that column is not NULL.
- COUNT(DISTINCT column_name) counts how many different non-NULL values exist.
Total number of employees
SELECT COUNT(*) AS total_employees
FROM Employees;Counting unique values
Adding DISTINCT inside COUNT is a quick way to measure variety rather than volume. For example, counting the distinct departments tells you how many teams exist, no matter how many people work in each one.
How many distinct departments
SELECT COUNT(DISTINCT department) AS department_count
FROM Employees;Counting per group
Pairing COUNT with GROUP BY produces a headcount for each category. This is one of the most common reporting patterns in SQL.
Number of employees per department
SELECT department, COUNT(*) AS headcount
FROM Employees
GROUP BY department;