Count DISTINCT in T-SQL: Syntax and Examples

How-to basics · Updated November 23, 2026

The COUNT(DISTINCT column_name) expression in T-SQL 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 orders. This is the direct answer; the rest of this article explains how it works, when to use it, and common pitfalls.

What COUNT(DISTINCT) Actually Counts

In T-SQL, COUNT(DISTINCT expression) evaluates the expression for each row in the result set, removes NULLs, and then counts the remaining distinct values. It is a combination of the COUNT aggregate and the DISTINCT keyword. The expression can be a single column, a concatenation of columns, or any valid scalar expression. For instance, COUNT(DISTINCT FirstName + ' ' + LastName) counts unique full names. Note that if the expression evaluates to NULL for a row, that row is ignored. Also, if the expression returns an empty string, it is counted as a value (empty strings are not NULL).

Syntax and Placement in a Query

The COUNT(DISTINCT ...) is used in the SELECT list, just like other aggregate functions. It can appear in a query with GROUP BY, HAVING, or without any grouping (in which case it returns a single value for the whole table). Example:

SELECT DepartmentID, COUNT(DISTINCT JobTitle) AS UniqueTitles
FROM HumanResources.Employee
GROUP BY DepartmentID;

This returns one row per department with the number of distinct job titles in that department. You can also use it with a WHERE clause to filter rows before counting. The syntax is always COUNT(DISTINCT expression) – note that there is no space between COUNT and the parenthesis, and DISTINCT is inside the parentheses. Do not write COUNT(DISTINCT(column)) with an extra parenthesis – that is valid but redundant.

How It Works Internally

When SQL Server executes a query with COUNT(DISTINCT column), it must identify unique values. Internally, this often involves a sort or a hash operation on the column’s values. For small tables, a sort is typical; for larger tables, a hash aggregate may be used. This means that COUNT(DISTINCT) can be more resource-intensive than a simple COUNT(*) or COUNT(column) because it requires deduplication. The performance impact grows with the number of rows and the size of the values. If you need to count distinct values frequently on a large table, consider creating an indexed view or using a pre-aggregated summary table, or using the APPROX_COUNT_DISTINCT function (see below).

Counting Distinct on Multiple Columns

Sometimes you need to count distinct combinations of two or more columns. T-SQL does not have a built-in COUNT(DISTINCT col1, col2) syntax. Instead, you concatenate the columns into a single expression. For example, to count distinct (City, State) pairs:

SELECT COUNT(DISTINCT City + '|' + State) AS UniqueCities
FROM Customers;

Using a separator like ‘|’ prevents ambiguity (e.g., ‘New York’ + ‘NY’ vs ‘New’ + ‘YorkNY’). Alternatively, you can use a subquery with SELECT DISTINCT and then count the rows:

SELECT COUNT(*) FROM (SELECT DISTINCT City, State FROM Customers) AS d;

Both methods give the same result, but the concatenation approach is often simpler in a single query, especially when grouping by other columns.

Common Pitfalls and Misconceptions

One common mistake is assuming COUNT(DISTINCT column) counts NULLs. It does not – NULLs are ignored. If you need to include NULL as a distinct value, you must convert it to a non-NULL placeholder, e.g., COUNT(DISTINCT ISNULL(column, 'NULL')). Another misconception is that COUNT(DISTINCT *) is valid – it is not; you must specify an expression. Also, be careful when using COUNT(DISTINCT) with floating-point numbers; due to rounding, two values that appear equal may be stored differently, leading to an overcount. For example, 0.1 + 0.2 might not equal 0.3 exactly. Use decimal types or round values before counting if needed.

Performance and Alternatives

For large datasets, COUNT(DISTINCT) can be slow because it requires a full scan and a sort or hash. SQL Server 2019 and later offer APPROX_COUNT_DISTINCT, which returns an approximate count with a small error rate (typically less than 2%). It is much faster because it uses a probabilistic data structure. Example:

SELECT APPROX_COUNT_DISTINCT(CustomerID) AS ApproxCustomers FROM Orders;

This is ideal for dashboards where a precise count is not critical. For exact counts, consider creating an indexed view with COUNT_BIG(DISTINCT ...) – but note that indexed views have many restrictions, and you must use WITH SCHEMABINDING. Alternatively, maintain a summary table that you update incrementally. If you only need to know whether a value exists, use EXISTS instead of counting.

Frequently Asked Questions

Can I use COUNT(DISTINCT) with a WHERE clause? Yes, the WHERE clause filters rows before the count is applied. For example, SELECT COUNT(DISTINCT ProductID) FROM Sales WHERE OrderDate > '2024-01-01'; counts distinct products sold after that date.

Why does COUNT(DISTINCT) return 0 for a column with only NULLs? Because NULLs are ignored. If all values are NULL, the distinct count is 0. If you want to count NULL as a value, use COUNT(DISTINCT ISNULL(column, 'NULL')).

What is the difference between COUNT(DISTINCT column) and COUNT(column)? COUNT(column) counts all non-NULL values, including duplicates. COUNT(DISTINCT column) counts only unique non-NULL values. For example, if a column has values (1,1,2,NULL), COUNT(column) returns 3, while COUNT(DISTINCT column) returns 2.

Does COUNT(DISTINCT) work with text or varchar columns? Yes, it works with any data type that supports equality comparison, including strings. However, be aware of collation settings, which affect case sensitivity and accent sensitivity. For example, in a case-insensitive collation, ‘ABC’ and ‘abc’ are considered the same, so they count as one distinct value.

Can I use COUNT(DISTINCT) in a HAVING clause? Yes, you can filter groups based on their distinct count. For example, SELECT DepartmentID FROM Employees GROUP BY DepartmentID HAVING COUNT(DISTINCT JobTitle) > 5; returns departments with more than 5 distinct job titles.

Is there a way to count distinct values across multiple columns without concatenation? Not directly, but you can use a subquery with UNION to get distinct combinations, or use the concatenation method shown above. The subquery approach is often clearer for many columns.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.