SQL Cookbook Lesson

How to count distinct values in SQL

Learn how to count distinct values in SQL with examples and explanations from SQLPad.

Problem

How can you count the distinct values in a SQL table?

Sample Data

Let's assume we have a table called Orders with the following data:

OrderID CustomerID OrderDate
1 3 2022-01-01
2 2 2022-01-02
3 1 2022-01-03
4 2 2022-01-04
5 3 2022-01-05
6 1 2022-01-06

In this case, we want to count the distinct CustomerID values.

MySQL Solution

SELECT COUNT(DISTINCT CustomerID) AS DistinctCustomers
FROM Orders;

PostgreSQL Solution

SELECT COUNT(DISTINCT CustomerID) AS DistinctCustomers
FROM Orders;

Explanation

Both MySQL and PostgreSQL use the same syntax for counting distinct values.

The DISTINCT keyword in SQL is used to return only distinct (different) values. In this case, it's used within the COUNT() function to count the distinct CustomerID values from the Orders table.

The AS keyword is used to rename the column in the result set. Without it, the result would just be labelled as COUNT(DISTINCT CustomerID). By using AS DistinctCustomers, we make the result set more readable by renaming the column to DistinctCustomers.

The result of the SQL statement will be the number of distinct customers. In the sample data, the number of distinct CustomerID values is 3, so the result would be:

DistinctCustomers
3

Keep Practicing

Related Cookbook Lessons

View all lessons

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.