The short answer: use SELECT COUNT(DISTINCT column_name) FROM table_name; to count unique non-NULL values in a column. This returns an integer representing how many distinct values exist, ignoring NULLs by default. The rest of this article explains how it works, when to use it, performance considerations, and common mistakes.
What COUNT(DISTINCT) Actually Counts
In SQL Server, COUNT(DISTINCT expression) evaluates the expression for each row in the group (or the whole table if no GROUP BY) and returns the number of unique non-NULL values. NULLs are not counted, and each distinct value is counted once, regardless of how many times it appears. For example, if a column has values (1, 1, 2, NULL, 3), the result is 3 (values 1, 2, and 3).
Note that COUNT(DISTINCT *) is not valid syntax—you must specify a column or expression. Also, the expression can be a computed value, like COUNT(DISTINCT YEAR(OrderDate)), which counts distinct years.
Basic Syntax and Examples
The syntax is straightforward:
SELECT COUNT(DISTINCT column_name) FROM schema.table;
Here are practical examples using a hypothetical Sales table with columns CustomerID, ProductID, and OrderDate:
- Count distinct customers:
SELECT COUNT(DISTINCT CustomerID) FROM Sales; - Count distinct products per customer:
SELECT CustomerID, COUNT(DISTINCT ProductID) FROM Sales GROUP BY CustomerID; - Count distinct order years:
SELECT COUNT(DISTINCT YEAR(OrderDate)) FROM Sales;
You can also combine with conditions: SELECT COUNT(DISTINCT CustomerID) FROM Sales WHERE OrderDate >= '2023-01-01';
How SQL Server Executes COUNT(DISTINCT)
Internally, SQL Server uses a sort or a hash aggregate to compute distinct counts. For small datasets, it sorts the values and scans for unique ones. For larger sets, it uses a hash table in memory (or spills to tempdb if memory is insufficient). This can be resource-intensive, especially on large tables or with wide expressions.
The execution plan shows a Stream Aggregate or Hash Match operator. If the column has an index, SQL Server may use that index to avoid sorting, but it still must scan all rows that match the predicate. There is no shortcut to count distinct without touching every qualifying row.
Performance Considerations and Alternatives
Counting distinct on a large table can be slow. Here are ways to improve performance:
- Use an index: A nonclustered index on the column (or included in a covering index) can help, but the query still scans the index.
- Approximate counts: For very large tables, use
APPROX_COUNT_DISTINCT(available in SQL Server 2019 and later). It returns an approximate value with a small error rate but runs much faster. Example:SELECT APPROX_COUNT_DISTINCT(CustomerID) FROM Sales; - Pre-aggregate: If you need the count frequently, maintain a summary table with distinct counts updated incrementally.
- Filter early: Apply WHERE clauses to reduce rows before the distinct operation.
Be aware that COUNT(DISTINCT) with multiple columns (e.g., COUNT(DISTINCT col1, col2)) is not supported in SQL Server—you must concatenate or use a subquery. For example: SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 FROM Sales) AS d;
Common Mistakes and Misconceptions
One frequent error is assuming COUNT(DISTINCT) counts NULLs. It does not. If you need to count NULLs as a distinct value, you must use a workaround like COUNT(DISTINCT ISNULL(col, 'NULL_PLACEHOLDER')), but be careful with type conversion.
Another mistake is using COUNT(DISTINCT) inside a subquery without understanding the scope. For example, SELECT COUNT(DISTINCT CustomerID) FROM Sales WHERE OrderDate > '2023-01-01' counts distinct customers who have orders after that date, not distinct orders.
Also, some users expect COUNT(DISTINCT) to work with text or large data types, but it works fine, though performance may suffer with large strings.
Comparing COUNT(DISTINCT) with Other Methods
Alternatives to get distinct counts include:
- GROUP BY with COUNT(*):
SELECT COUNT(*) FROM (SELECT CustomerID FROM Sales GROUP BY CustomerID) AS t;This is essentially the same as COUNT(DISTINCT) but can be more flexible if you need additional columns. - ROW_NUMBER() with PARTITION BY: Useful for counting distinct combinations but overkill for simple counts.
- APPROX_COUNT_DISTINCT: As mentioned, for approximate results with better performance.
In terms of accuracy, COUNT(DISTINCT) is exact; the approximate version is not. Choose based on your need for precision versus speed.
Frequently Asked Questions
Does COUNT(DISTINCT) include NULL values?
No. By default, NULL values are ignored. If you need to count NULLs as a distinct value, you must convert them to a non-NULL placeholder, but this can skew results if the placeholder collides with real values.
Can I use COUNT(DISTINCT) with multiple columns?
SQL Server does not support COUNT(DISTINCT col1, col2) directly. Use a subquery with SELECT DISTINCT on the columns, then count the rows.
What is the difference between COUNT(DISTINCT) and COUNT(*)?
COUNT(*) counts all rows in the group, including NULLs and duplicates. COUNT(DISTINCT column) counts unique non-NULL values in that column. They answer different questions.
How can I speed up COUNT(DISTINCT) on a large table?
Consider using APPROX_COUNT_DISTINCT if you can tolerate approximate results, create appropriate indexes, filter rows early, or maintain a precomputed summary table. Also, ensure your query is not scanning more data than necessary.
Is APPROX_COUNT_DISTINCT accurate enough?
It has a maximum error rate of about 2% for a 99% confidence level, but in practice the error is often much smaller. It is not suitable for financial reporting where exact numbers are required, but it is great for dashboards and exploratory queries.
Best Practices and Final Thoughts
Use COUNT(DISTINCT) when you need exact distinct counts and your dataset is reasonably sized. For very large tables, test with APPROX_COUNT_DISTINCT to see if the accuracy is acceptable. Always check the execution plan to see if sorts or spills are occurring, and consider indexing strategies. Remember that COUNT(DISTINCT) ignores NULLs, which is usually what you want, but be explicit in your documentation so others understand.
Related
- Update Dictionary in Python Syntax
- Business Central Split String: How to Do It
- SQL COUNT DISTINCT Values: Syntax & Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Snowflake LATERAL SPLIT_TO_TABLE: Syntax and ExamplesYes. In Snowflake, use LATERAL SPLIT_TO_TABLE in the FROM clause to turn a delimited string in each source…
- Excel Ctrl Shortcuts: Essential Keys ExplainedIn Excel for Microsoft 365 on Windows, Ctrl shortcuts are key combinations that speed up common tasks: press…
- How to Add a Header to One Page Only in Microsoft WordTo put a header on just one page in Word, isolate that page in its own section with…
- SOLIDWORKS Split Tool: How to Split and Save BodiesTo use the SOLIDWORKS Split tool, open a part, choose Insert > Features > Split, select a plane,…
- Laundry List Template in Excel: Build and Use OneYes. A laundry list template in Excel can track clothes or household laundry tasks by date, load, person,…
- Advanced Filter in Google Sheets: Methods and ExamplesGoogle Sheets does not have a single command named “Advanced Filter” like Microsoft Excel. To filter a table…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.