COUNT function in SQL

The COUNT function in SQL is used to count the number of rows in a table or in a query.

Note: The count function returns the count of non-null values in a specified column, it ignores the null values.

SQL Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

Example: Let's consider a simple example using a table called employees.

employee_idfirst_namelast_namedepartment
1JohnDoeSales
2JaneSmithMarketing
3MichaelO'ConnorSales
4SarahO'BrienHR
5LauraWilsonSales

Count Total Number of Employees

To count the total number of employees in the employees table:

SQL

SELECT COUNT(*) AS total_employees
FROM employees;

The result of the above query is shown below, which returns the total number of rows in the employees table.

total_employees
5

Count Number of Employees in Sales Department

To count the number of employees in the Sales department:

SQL

SELECT COUNT(*) AS sales_employees
FROM employees
WHERE department = 'Sales';

The result of the above query counts the number of rows where the department is 'Sales'.

sales_employees
3

Count Distinct Values in a Column

To count the number of distinct departments:

SQL

SELECT COUNT(DISTINCT department) AS distinct_departments
FROM employees;

The result of the above query is shown below:

distinct_departments
3

This query counts the number of unique values in the department column, which are 'Sales', 'Marketing', and 'HR'.