In Microsoft SQL Server, COUNT(DISTINCT column_name) returns the number of unique, non-NULL values in a column or expression. For example, SELECT COUNT(DISTINCT CustomerID) FROM Orders; counts how many different customers have placed at least one order. This function is a core part of SQL Server’s aggregate functions and is essential for answering “how many unique…” questions in your data.
What COUNT(DISTINCT) Actually Does
COUNT(DISTINCT expression) evaluates the expression for each row in the group (or the whole table if no GROUP BY), removes all NULL values, and then counts the remaining distinct values. It is different from COUNT(*), which counts every row, and COUNT(column), which counts non-NULL values but includes duplicates.
Key behaviors to remember:
- NULL values are ignored – they never count towards the distinct total.
- If all values in the column are NULL,
COUNT(DISTINCT)returns 0. - The result is always an integer (or
bigintif the count exceeds 2,147,483,647). - It works on multiple columns too:
COUNT(DISTINCT col1, col2)counts distinct combinations of values from both columns.
Basic Syntax and Examples
The general syntax is:
SELECT COUNT(DISTINCT column_name) FROM table_name WHERE condition;
Here are a few practical examples using a hypothetical Sales table with columns OrderID, CustomerID, ProductID, and SaleDate:
- Count unique customers:
SELECT COUNT(DISTINCT CustomerID) FROM Sales; - Count unique products sold in 2023:
SELECT COUNT(DISTINCT ProductID) FROM Sales WHERE YEAR(SaleDate) = 2023; - Count distinct combinations of customer and product:
SELECT COUNT(DISTINCT CustomerID, ProductID) FROM Sales;– this returns how many different customer-product pairs exist.
Using COUNT(DISTINCT) with GROUP BY
When you need a distinct count per group, combine COUNT(DISTINCT) with GROUP BY. For example, to get the number of distinct customers per product:
SELECT ProductID, COUNT(DISTINCT CustomerID) AS UniqueCustomers
FROM Sales
GROUP BY ProductID;
This returns one row per product, with the count of unique customers who bought that product. You can also use HAVING to filter groups based on the distinct count, such as HAVING COUNT(DISTINCT CustomerID) > 10 to see only products with more than 10 unique buyers.
Performance Considerations and Alternatives
COUNT(DISTINCT) can be slow on large tables because SQL Server must sort or hash the distinct values. For columns with a large number of distinct values (high cardinality), the operation can be resource-intensive. Here are some tips:
- Ensure the column is indexed – an index can help but does not always eliminate the sorting cost.
- Filter rows with
WHEREto reduce the dataset before counting. - If you need approximate counts for very large datasets, consider using
APPROX_COUNT_DISTINCT(available in Azure SQL Database and SQL Server 2019+). It returns an approximate value with a small error margin but is much faster. - For repeated counts on static data, consider precomputing the distinct counts in a summary table.
Common Pitfalls and Misconceptions
One common mistake is expecting COUNT(DISTINCT) to count NULLs. It does not. If you need to count NULLs separately, you must use a different approach, such as SUM(CASE WHEN col IS NULL THEN 1 ELSE 0 END).
Another misconception is that COUNT(DISTINCT col) is the same as COUNT(col) when the column has no duplicates. That is true, but when duplicates exist, COUNT(DISTINCT) returns fewer rows. Also, be careful with data types: COUNT(DISTINCT) works on text, numbers, dates, and most other data types, but not on text, ntext, or image columns in older SQL Server versions (use varchar(max) instead).
Finally, note that COUNT(DISTINCT) is not supported in all SQL dialects. For example, MySQL and PostgreSQL support it, but older versions of Microsoft Access do not. In SQL Server, it has been supported since at least SQL Server 2000.
COUNT(DISTINCT) vs. Other Counting Methods
To choose the right counting method, understand the differences:
COUNT(*)– counts all rows in the group, including rows with NULLs.COUNT(column)– counts non-NULL values, but duplicates are counted multiple times.COUNT(DISTINCT column)– counts unique non-NULL values.
For example, if a column has values (1, 1, 2, NULL), COUNT(*) returns 4, COUNT(column) returns 3, and COUNT(DISTINCT column) returns 2. Use COUNT(DISTINCT) when you need the number of unique items, such as unique visitors, unique products, or unique combinations.
Frequently Asked Questions
Can I use COUNT(DISTINCT) with multiple columns?
Yes, SQL Server supports COUNT(DISTINCT col1, col2), which counts distinct pairs of values. This is useful for counting unique combinations, like how many different customer-product pairs exist. Note that NULLs in any column cause that combination to be ignored.
How do I count distinct values with a condition?
Use a WHERE clause to filter rows before counting. For example, SELECT COUNT(DISTINCT CustomerID) FROM Sales WHERE SaleDate > '2023-01-01'; counts unique customers who purchased after that date. If you need a conditional count within the same query without filtering other rows, use COUNT(DISTINCT CASE WHEN condition THEN column END).
Why is COUNT(DISTINCT) slow on my large table?
Because SQL Server must identify unique values, which often requires sorting or hashing the entire column. The larger the table and the higher the cardinality, the slower it gets. Use APPROX_COUNT_DISTINCT for faster approximate results, or pre-aggregate data into a summary table if exact counts are needed repeatedly.
Does COUNT(DISTINCT) include NULL values?
No, NULL values are ignored. If you need to include NULLs as a distinct value, you can use COUNT(DISTINCT ISNULL(column, 'NULL_PLACEHOLDER')), but be careful with data types.
What is the difference between COUNT(DISTINCT) and DISTINCT COUNT?
There is no standard “DISTINCT COUNT” in SQL. You might see SELECT DISTINCT COUNT(column) in some code, but that is incorrect – it first counts all non-NULL values (including duplicates) and then removes duplicate counts, which is almost never what you want. Always use COUNT(DISTINCT column).
Can I use COUNT(DISTINCT) in a window function?
Yes, SQL Server supports COUNT(DISTINCT) as a window function with an OVER clause, for example: SELECT OrderID, COUNT(DISTINCT CustomerID) OVER (PARTITION BY ProductID) AS UniqueCustomersPerProduct FROM Sales;. This gives a running or grouped distinct count without collapsing rows.