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
FROM table_name
WHERE condition;
Example: Let's consider a simple example using a table called employees.
employee_id | first_name | last_name | department |
---|---|---|---|
1 | John | Doe | Sales |
2 | Jane | Smith | Marketing |
3 | Michael | O'Connor | Sales |
4 | Sarah | O'Brien | HR |
5 | Laura | Wilson | Sales |
Count Total Number of Employees
To count the total number of employees in the employees table:
SQL
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
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
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'.