Skip to content

SQL COUNT Function

Syntax

The COUNT function in SQL is used to return the number of rows or non-NULL values in a column.

-- Count all rows in a table
SELECT COUNT(*)
FROM table_name;
-- Count non-NULL values in a specific column
SELECT COUNT(column1)
FROM table_name;
-- Count distinct values in a column
SELECT COUNT(DISTINCT column1)
FROM table_name;

Example

-- Count all rows in the employees table
SELECT COUNT(*)
FROM employees;
/* Output:
| COUNT(*) |
|----------|
| 3 |
*/
-- Count non-NULL values in the age column
SELECT COUNT(age)
FROM employees;
/* Output:
| COUNT(age) |
|------------|
| 2 |
*/
-- Count distinct departments
SELECT COUNT(DISTINCT department)
FROM employees;
/* Output:
| COUNT(DISTINCT department) |
|----------------------------|
| 3 |
*/