Get the number of rows in a table in SQL

February 20, 2019

Regardless of the flavour, SQL databases come with many useful aggregate functions that can come in handy and save many lines of code in your queries. One of these functions is the COUNT() function. Here's how to use it...

Basic example:

The query below gets you the number of all the rows in the Employees table.

SELECT COUNT(*)
FROM Employees

Distinct rows:

SELECT COUNT(DISTINCT employee_id)
FROM Employees

Using GROUP BY:

SELECT salary_range, COUNT(*)
FROM Employees
GROUP BY salary_range

Using GROUP BY and ORDER BY:

SELECT employment_rank, salary_range, COUNT(*)
FROM Employees
GROUP BY salary_range
ORDER BY employment_rank DESC