COUNT Function - SQL


Overview


The COUNT function in SQL returns the number of rows that match a specified condition, or the total number of rows in a table if no condition is given. It is commonly used in SELECT statements to count entries, facilitating data analysis and reporting.

Example:

SELECT COUNT(*)
FROM company.employees
WHERE department_id = 1

Syntax:

SELECT COUNT(column_name)
FROM table_name
[WHERE condition]

This counts the number of non-NULL values in column_name from table_name that meet the specified condition. In this syntax, the WHERE Statement is optional; if omitted, the COUNT function will count the values for all rows in the table.

Sample Data:

department_id salary
3 123000
2 135000
3 115000
NULL 115000
2 125000
1 120000
1 105000
5 200000
2 107000
1 100000

Example: Without the WHERE Statement


In this example, we are counting how many rows are in the company.employees table. The final result is 10, which means there are 10 employees in the table.


Example: With the WHERE Statement


In this example, we are counting how many rows are in the company.employees table where the department_id column equals 1. The final result is 3, which means there are 3 employees in department_id 1.