SQL SELECT DISTINCT COUNT: How to Count Unique Values

Formulas & functions · Updated November 23, 2026

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:

  1. Basic count: SELECT COUNT(DISTINCT category) FROM products;
  2. With GROUP BY: SELECT department, COUNT(DISTINCT employee_id) FROM assignments GROUP BY department; – counts distinct employees per department.
  3. With HAVING: SELECT department, COUNT(DISTINCT employee_id) AS emp_count FROM assignments GROUP BY department HAVING COUNT(DISTINCT employee_id) > 5;
  4. 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_DISTINCT in SQL Server, COUNT(DISTINCT) with HyperLogLog in Postgres (via extension), or APPROX_DISTINCT in 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_DISTINCT for large datasets (SQL Server 2019+).
  • PostgreSQL: Standard COUNT(DISTINCT) works; for approximate, use COUNT(DISTINCT) with the hyperloglog extension or approx_count_distinct in 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

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

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

Spotted an error in this guide? Let us know.