Aggregate - COUNT

The COUNT() function returns the number of rows that matches a specified criteria, including the NULL values

Note - If you specify a column name instead of (*), NULL values will not be counted.

SELECT COUNT(column_name)/ COUNT(*)
FROM table_name;

!!! Database used in the below examples is

Aggregatechevron-right
  1. Add a WHERE clause to add a condition before counting/ aggregation

SELECT COUNT(column_name)
FROM table_name 
WHERE condition 1;

SELECT COUNT(name)
FROM employees
WHERE salary > 65000;
  1. To ignore the duplicate values, use the DISTINCT keyword in the COUNT function

In the Example below, it is used to count the different values of salaries, avoiding the one that are repeated.

SELECT COUNT(DISTINCT column_name)
FROM table_name;

SELECT COUNT(DISTINCT salary)
FROM employees;
  1. Use an alias using the keyword AS to make the records simpler by counting all the rows, including the NULL values

  1. Using COUNT BY with GROUP BY

In the Example below, the query counts the number of employees in each department. It groups the employees by department and applies COUNT(*) to each group separately.

Last updated