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;
Note: The difference between COUNT(*) and COUNT(column) matters when a column has NULLs. COUNT(*) counts the row regardless, while COUNT(column) skips rows where that column is empty.

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;
ExpressionWhat it countsIncludes NULL?
COUNT(*)All rowsYes
COUNT(salary)Rows with a salary valueNo
COUNT(DISTINCT department)Distinct department valuesNo