COUNT(DISTINCT column) counts the unique non-NULL values contained in a column.
Counting unique customers, products, accounts, or regions is a common business requirement.
Count the number of unique customers who placed orders.
SELECT
COUNT(DISTINCT CustomerID) AS UniqueCustomers
FROM Orders;
Analysts use COUNT DISTINCT for unique customer counts, active users, products sold, branches, and other business metrics.
- COUNT DISTINCT counts unique values.
- Duplicate values are counted once.
- NULL values are generally excluded.
- It is useful for customer and entity analysis.
- It can be combined with GROUP BY.
What is COUNT(DISTINCT) used for?
It counts the number of unique non-NULL values in a column.
What is the difference between COUNT(*) and COUNT(DISTINCT CustomerID)?
COUNT(*) counts rows, while COUNT(DISTINCT CustomerID) counts unique customer IDs.