The short answer: to count unique values in SQL, use SELECT COUNT(DISTINCT column_name) FROM table_name;. This returns the number of distinct (non-null) values in that column. For example, SELECT COUNT(DISTINCT country) FROM customers; gives the number of different countries in the customers table.
What COUNT(DISTINCT) Actually Does
COUNT(DISTINCT expression) evaluates the expression for each row, removes duplicates and NULLs, then counts the remaining rows. It works on single columns, multiple columns (as a combined expression), or expressions like UPPER(name) or YEAR(order_date). The result is always an integer.
Key behavior:
- NULLs are ignored – if a column has 100 rows but 10 are NULL, COUNT(DISTINCT) only counts the 90 non-null values.
- It counts unique combinations when you list multiple columns:
COUNT(DISTINCT col1, col2)counts each distinct pair. - It is not the same as
COUNT(*)which counts all rows including duplicates and NULLs.
How to Use COUNT(DISTINCT) in Queries
You can use it anywhere an aggregate function is allowed: in a SELECT list, with GROUP BY, HAVING, or even in a subquery. Here are common patterns:
- Basic count:
SELECT COUNT(DISTINCT category) FROM products; - With GROUP BY:
SELECT department, COUNT(DISTINCT employee_id) FROM assignments GROUP BY department;– counts distinct employees per department. - With HAVING:
SELECT department, COUNT(DISTINCT employee_id) AS emp_count FROM assignments GROUP BY department HAVING COUNT(DISTINCT employee_id) > 5; - As a subquery:
SELECT * FROM orders WHERE customer_id IN (SELECT DISTINCT customer_id FROM orders WHERE order_date > '2024-01-01');– but that’s not counting, just filtering.
COUNT(DISTINCT) vs. COUNT(*) vs. COUNT(column)
These three look similar but answer different questions:
COUNT(*)– counts every row, including duplicates and NULLs. Use when you need total rows.COUNT(column)– counts non-NULL values in that column, but duplicates are counted multiple times.COUNT(DISTINCT column)– counts unique non-NULL values.
Example: a table with 10 rows, column A has values (1,1,2,NULL,3,3,4,5,5,5). Results: COUNT(*) = 10, COUNT(A) = 9 (NULL ignored), COUNT(DISTINCT A) = 5 (1,2,3,4,5).
Common Mistakes and Performance Pitfalls
One frequent mistake is assuming COUNT(DISTINCT) counts all unique values including NULLs – it doesn’t. If you need to count NULL as a distinct value, you must handle it explicitly, e.g., COUNT(DISTINCT COALESCE(column, 'NULL_PLACEHOLDER')) – but that’s a workaround, not standard.
Performance: COUNT(DISTINCT) can be slow on large tables because the database must sort or hash all values to find duplicates. On millions of rows, this can be a bottleneck. Mitigations:
- Add an index on the column(s) – helps some databases.
- Use approximate functions if exactness isn’t critical: e.g.,
APPROX_COUNT_DISTINCTin SQL Server,COUNT(DISTINCT)with HyperLogLog in Postgres (via extension), orAPPROX_DISTINCTin BigQuery. - Pre-aggregate in a temp table if you run the query repeatedly.
Database-Specific Variations
While the syntax is standard, some databases have quirks:
- SQL Server: Supports COUNT(DISTINCT) but also offers
APPROX_COUNT_DISTINCTfor large datasets (SQL Server 2019+). - PostgreSQL: Standard COUNT(DISTINCT) works; for approximate, use
COUNT(DISTINCT)with thehyperloglogextension orapprox_count_distinctin some cloud versions. - MySQL: COUNT(DISTINCT) works fine; no built-in approximate version until recently (MySQL 8.0.31 has
APPROX_COUNT_DISTINCT). - Oracle: Supports COUNT(DISTINCT) and also
COUNT(DISTINCT ...) OVER (PARTITION BY ...)for window counts. - SQLite: COUNT(DISTINCT) is supported, but note that it counts NULLs as distinct in some older versions? Actually SQLite treats NULLs as distinct when using DISTINCT, so COUNT(DISTINCT col) includes NULL if present – a difference from standard. Test your version.
Always check your database documentation for exact NULL handling.
Counting Distinct Values Across Multiple Columns
To count unique combinations of two or more columns, use COUNT(DISTINCT col1, col2). For example, in a sales table, to count unique customer-product pairs: SELECT COUNT(DISTINCT customer_id, product_id) FROM sales; This counts each combination once, ignoring NULLs in any column.
If you need to count distinct values per group, combine with GROUP BY. For instance, to get the number of unique products sold per category: SELECT category, COUNT(DISTINCT product_id) FROM products GROUP BY category;
Alternatives to COUNT(DISTINCT)
Sometimes you need a different approach:
- Using a subquery:
SELECT COUNT(*) FROM (SELECT DISTINCT column FROM table) AS sub;– equivalent but sometimes clearer for complex expressions. - Using GROUP BY:
SELECT COUNT(*) FROM (SELECT column FROM table GROUP BY column) AS sub;– same result, but GROUP BY can be faster in some databases. - Using window functions: For running counts of distinct values, use
COUNT(DISTINCT column) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)– but not all databases support DISTINCT in window functions (SQL Server does, MySQL doesn’t). - Approximate counts: When exactness isn’t needed, use database-specific approximate functions to get near-instant results on huge datasets.
Frequently Asked Questions
Does COUNT(DISTINCT) include NULL? No, standard SQL ignores NULLs. If you need to count NULL as a distinct value, use a workaround like COUNT(DISTINCT COALESCE(col, 'NULL')) – but that changes the data type.
Can I use COUNT(DISTINCT) with a WHERE clause? Yes, it works like any aggregate: SELECT COUNT(DISTINCT category) FROM products WHERE price > 100; counts distinct categories among expensive products.
What’s the difference between COUNT(DISTINCT col) and COUNT(DISTINCT col1, col2)? The first counts unique values in one column; the second counts unique combinations of both columns. For example, if col1 has (A,B) and col2 has (X,Y), the combinations could be (A,X) and (B,Y) – two distinct pairs, even if A and B are unique.
Why is COUNT(DISTINCT) slow on big tables? The database must scan all values, sort or hash them to find duplicates, which is O(n log n) or O(n) but with memory overhead. Indexes can help, but for millions of rows, consider approximate functions.
Can I use COUNT(DISTINCT) in a HAVING clause? Yes, for example: SELECT department FROM employees GROUP BY department HAVING COUNT(DISTINCT job_title) > 3; returns departments with more than 3 distinct job titles.
Does COUNT(DISTINCT) work on text columns? Yes, it works on any data type that supports equality comparison, including strings, numbers, dates, and even binary data. For text, it’s case-sensitive in most databases unless you use a case-insensitive collation.
Related
- Federal Reserve Weekly Balance Sheet Explained
- VLOOKUP in Google Sheets: Example & How to Use
- Python String Z-Transform: What It Is & How to Use It
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Split Cell by Character: Methods and FormulasTo split a cell at a repeated separator such as a comma, hyphen, or space, select the cells…
- COUNTIFS Does Not Contain: Excel Formula and ExamplesTo count cells that do not contain a particular text string in Excel, use a COUNTIFS criterion with…
- Excel SUMIF Based on Cell Value: Formula & ExamplesThe direct answer: use =SUMIF(range, criteria, [sum_range]), where range is the cells you check against a condition, criteria…
- Filter Excel by Date: Steps, Custom Ranges, and FixesTo filter dates in Excel for Microsoft 365 on Windows, select a cell in your data, choose Data…
- VLOOKUP Formula Examples in Excel: Exact and ApproximateIn Excel, VLOOKUP searches the first column of a range and returns a value from another column in…
- Excel IFERROR vs ISERROR: Which Should You Use?Use IFERROR when you want to replace an error with a value such as a message or blank-looking…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.