SQL COUNT()Function
The COUNT()
function in SQL is used to return the number of rows that match a specified condition. It can be used with SELECT
statements to count rows in a table, including duplicate values and NULL
s.
Here’s a basic syntax of the COUNT()
function:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Examples:
1. Counting all rows in a table
Suppose we have a table called employees
:
id |
name |
department |
1 |
Alice |
HR |
2 |
Bob |
IT |
3 |
Charlie |
HR |
4 |
David |
Finance |
5 |
Eve |
IT |
To count the total number of rows in the employees
table, we can use:
SELECT COUNT(*) FROM employees;
Output:
2. Counting rows with a specific condition
To count the number of employees in the IT department:
SELECT COUNT(*) FROM employees WHERE department = 'IT';
Output:
3. Counting distinct values
To count the number of distinct departments:
SELECT COUNT(DISTINCT department) FROM employees;
Output:
COUNT(DISTINCT department) |
3 |
4. Counting non-NULL values in a column
To count the number of non-NULL values in the department
column:
SELECT COUNT(department) FROM employees;
Output:
This function is useful for generating reports and obtaining statistical data about the data in your database.