The fastest way to count unique values in SQL is to use COUNT(DISTINCT column_name) in a query like SELECT COUNT(DISTINCT status) FROM orders;. This returns the number of distinct non-NULL values in that column; for a count that includes NULLs, or for counting unique combinations of multiple columns, you need different techniques, which are covered below.
Why Counting Unique Values Matters
Counting distinct values is a core analytical task. You might need to know how many unique customers made a purchase, how many different products were sold in a region, or how many distinct error codes appeared in a log. The result drives business decisions, so it is worth understanding exactly what your database counts and how to get the precise number you need. The most common mistake is assuming COUNT(column) counts unique values—it does not. It counts all non-NULL values, including duplicates.
The Basic: COUNT(DISTINCT column)
The standard SQL function COUNT(DISTINCT expression) is supported by virtually every relational database, including MySQL, PostgreSQL, SQL Server, Oracle, and SQLite. It counts the number of distinct, non-NULL values in a column or expression.
Example: Suppose you have a table sales with columns customer_id and region.
SELECT COUNT(DISTINCT customer_id) AS unique_customers
FROM sales;
If customer_id has values (101, 102, 101, 103, NULL), the result is 3, because NULL is ignored. If you need to include NULL as a distinct value, you can use a CASE expression or a subquery, as shown later.
Counting Unique Combinations of Multiple Columns
Sometimes you need the number of distinct pairs (or triples) of values. For example, count how many unique combinations of (product_id, store_id) appear in a sales table. COUNT(DISTINCT product_id, store_id) is valid in some databases (like PostgreSQL and SQLite), but not in others (like MySQL before 8.0.31 or SQL Server). A portable solution is to concatenate the columns into a single string, but that risks collisions (e.g., ‘1-23′ vs ’12-3’). A safer approach is to use a subquery:
SELECT COUNT(*) AS unique_combos
FROM (
SELECT DISTINCT product_id, store_id
FROM sales
) AS sub;
This works everywhere. The subquery returns distinct pairs, and the outer query counts them. Note that if a column contains NULL, DISTINCT treats NULLs as a single distinct value, so the count includes one row for NULL pairs.
Including NULLs in the Count
By default, COUNT(DISTINCT col) ignores NULLs. To count NULL as a distinct value, you can use a CASE expression to convert NULL to a literal:
SELECT COUNT(DISTINCT CASE WHEN col IS NULL THEN 'NULL' ELSE col END) AS distinct_with_null
FROM table;
This counts every distinct value plus one extra if any NULL exists. Alternatively, you can use a subquery with UNION to add a NULL row if needed, but the CASE method is simplest.
Performance Considerations and Alternatives
Counting distinct values can be expensive on large tables because the database must scan and sort or hash all values. For a single column, an index on that column can speed up the count. However, COUNT(DISTINCT) often forces a full scan if the column is not indexed. In PostgreSQL, you can use COUNT(DISTINCT) with an index; in MySQL, it may use an index for COUNT(DISTINCT) if the column is the leading part of an index. For approximate counts on very large datasets, some databases offer APPROX_COUNT_DISTINCT (SQL Server, BigQuery) or COUNT(DISTINCT) with HLL functions (PostgreSQL extension). These return an estimate that is usually close enough for dashboards.
If you need to count distinct values per group, use GROUP BY:
SELECT region, COUNT(DISTINCT customer_id) AS unique_customers
FROM sales
GROUP BY region;
Common Pitfalls and Misconceptions
- COUNT(column) vs COUNT(DISTINCT column) –
COUNT(column)counts non-NULL values, not unique ones. Always include DISTINCT. - COUNT(DISTINCT *) – Not valid in most databases. Use a subquery with
SELECT DISTINCT *and then count. - Whitespace and case sensitivity – ‘Apple’ and ‘apple’ are different in a case-sensitive database (like PostgreSQL with a case-sensitive collation). Use
LOWER(column)if you want case-insensitive counting. - NULLs in multiple columns – In a subquery with
SELECT DISTINCT, rows with NULL in any column are considered distinct from rows with non-NULL values, but all-NULL rows collapse to one. - Counting unique values across columns – If you want to count distinct values that appear in any of several columns, you need to unpivot first (e.g., using
UNION ALLorCROSS APPLYin SQL Server).
Database-Specific Notes
- MySQL:
COUNT(DISTINCT)works, but before MySQL 8.0.31 you cannot use multiple expressions inside it. Use a subquery. - PostgreSQL: Supports
COUNT(DISTINCT a, b)directly, and also offersCOUNT(DISTINCT)withFILTERfor conditional counts. - SQL Server:
COUNT(DISTINCT)works, but for multiple columns you must use a subquery. SQL Server also hasAPPROX_COUNT_DISTINCTfor large datasets. - SQLite: Supports
COUNT(DISTINCT col)and alsoCOUNT(DISTINCT col1, col2). - Oracle: Supports
COUNT(DISTINCT col)andCOUNT(DISTINCT col1, col2)(as of recent versions).
Frequently Asked Questions
How do I count unique values in a column with NULLs included?
Use COUNT(DISTINCT COALESCE(col, 'NULL')) to treat NULL as a literal string, but be careful if your data already contains the string ‘NULL’. A safer method is to use a subquery: SELECT COUNT(DISTINCT val) FROM (SELECT col AS val FROM table UNION SELECT NULL) t; but this adds a NULL row even if none exists. The CASE method is most precise.
What is the difference between COUNT(DISTINCT) and COUNT(*) with GROUP BY?
COUNT(DISTINCT col) returns a single number of distinct values across the whole table. COUNT(*) with GROUP BY col returns one row per distinct value with the count of rows for each. They answer different questions: the first gives a total, the second gives a breakdown.
Can I count unique values across multiple columns as a single count?
Yes, but the method depends on the database. In PostgreSQL and SQLite, you can use COUNT(DISTINCT col1, col2). In others, use a subquery with SELECT DISTINCT col1, col2 and then count the rows.
Why is my COUNT(DISTINCT) query slow?
Because the database must scan all rows and sort or hash the values. Adding an index on the column can help, but for very large tables, an approximate count may be faster. Also, avoid using DISTINCT on expressions like LOWER(col) because it prevents index usage unless you create a functional index.
How do I count distinct values per group in SQL?
Use GROUP BY with COUNT(DISTINCT col): SELECT group_col, COUNT(DISTINCT value_col) FROM table GROUP BY group_col;. This gives a separate distinct count for each group.
Related
- Oracle String to Number: TO_NUMBER and Casting Guide
- Importance of Data Entry: Why It Matters
- Milwaukee M12 Fuel Impact Driver: What to Know
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Word Count Formula: Count Words in Cells and TextTo count words in a cell in Excel, use =IF(TRIM(A2)="",0,LEN(TRIM(A2))-LEN(SUBSTITUTE(TRIM(A2)," ",""))+1), replacing A2 with the cell you want…
- COUNTIF Between Two Values in Excel (Step-by-Step)The simplest way to count cells between two values in Excel is to use the COUNTIFS function with…
- Conditional Formatting in Excel: If-Then Color RulesYes. In Excel, select the cells you want to format, then choose Home > Conditional Formatting and create…
- Excel Formula Greyed Out? Causes and FixesIf Excel’s formula commands are greyed out, first press Esc to leave cell-edit mode, then select a worksheet…
- SQL Server Split Function: STRING_SPLIT ExplainedSQL Server’s built-in split function is STRING_SPLIT, which turns a delimited string into a table of values. Use…
- Excel LEFT Function: Extract Text from the Left SideTo extract characters from the beginning of a cell in Excel, use the LEFT function. If A2 contains…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.