The COUNT
function in SQL is used to return the number of rows in a result set. It can count all rows or only those that meet a specific condition.
Key Points
Counts Rows:
TheCOUNT
function calculates the total number of rows in a table or result set, either including or excludingNULL
values based on the usage.Flexible with Conditions:
You can useCOUNT
with conditions in theWHERE
clause or with specific columns to get targeted counts.
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example
Counting All Rows
SELECT COUNT(*)
FROM employees;
- This query returns the total number of rows in the
employees
table, including rows withNULL
values.
Counting Non-NULL Values in a Column
SELECT COUNT(salary)
FROM employees;
- This query returns the number of rows where the
salary
column is notNULL
.
Counting Rows with a Condition
SELECT COUNT(*)
FROM employees
WHERE department = 'HR';
- This query counts rows where the
department
is 'HR'.
When to Use COUNT
To determine the total number of rows in a table or a filtered subset.
To measure data completeness by checking for
NULL
values in a column.