Beginner

62. COUNT DISTINCT

Learn how to count unique values using COUNT with DISTINCT.

📘 Lesson 62 of 728 ⏱ 7 min 🎯 Beginner

COUNT(DISTINCT column_name) counts the unique non-null values in a column. It is useful when duplicate values exist but the analysis requires the number of distinct items.

Business datasets often contain repeated values. For example, one customer may place many orders. COUNT(DISTINCT) allows analysts to count unique customers instead of total transactions.

If the Orders table contains multiple orders from the same customer, COUNT(DISTINCT CustomerID) can determine how many unique customers placed orders.

SQL
SELECT
    COUNT(DISTINCT CustomerID) AS UniqueCustomers
FROM Orders;

COUNT DISTINCT is useful for unique customers, active users, branches, products, accounts, employees, and other distinct business entities.

  • COUNT(DISTINCT) counts unique values.
  • Duplicate values are counted only once.
  • NULL values are not counted.
  • It is useful for customer and transaction analysis.
  • It can be combined with GROUP BY.
What does COUNT(DISTINCT) do?

It counts the unique non-null values in a specified column.

Why use COUNT(DISTINCT CustomerID)?

It counts unique customers instead of counting every transaction or order.

Have you finished this lesson?

Introduction to SQL – All Lessons