Case When Count Distinct SQL: Syntax & Examples

How-to basics · Updated November 23, 2026

The direct answer: COUNT(DISTINCT ...) counts unique non-null values in a column, and you combine it with CASE WHEN inside the COUNT function to count distinct values that meet a condition. For example, COUNT(DISTINCT CASE WHEN status = 'active' THEN user_id END) returns the number of unique active users. This pattern is standard SQL and works in PostgreSQL, MySQL, SQL Server, and Oracle, with minor syntax differences in some databases.

Why Combine CASE WHEN with COUNT DISTINCT

Plain COUNT(DISTINCT column) counts every unique value in that column across all rows. But real questions are conditional: “How many distinct customers bought in January?” or “How many unique products were sold in each region?” You could write a subquery with a WHERE clause, then count distinct from that result. That works, but it’s verbose and often slower. The CASE WHEN inside COUNT(DISTINCT ...) lets you do it in a single pass over the table, which is both cleaner and frequently more efficient because the database engine scans the data once instead of twice.

How the CASE WHEN Inside COUNT Works

The trick is that CASE returns a value when the condition is true, and returns NULL when false (if you omit the ELSE clause). COUNT ignores NULLs, so only rows that match the condition contribute to the distinct count. If you include an ELSE with a non-NULL value, those rows also get counted, which usually defeats the purpose. So the standard pattern is:

COUNT(DISTINCT CASE WHEN condition THEN column_to_count END)

For example, with a sales table orders(order_id, customer_id, order_date, amount), to count distinct customers who ordered in 2024:

SELECT COUNT(DISTINCT CASE WHEN order_date >= '2024-01-01' AND order_date < '2025-01-01' THEN customer_id END) AS active_customers_2024
FROM orders;

If a customer placed three orders in 2024, they appear three times in the CASE result, but DISTINCT collapses them to one. Customers with no 2024 orders get NULL, which is ignored.

Counting Distinct Combinations with CASE

Sometimes you need to count distinct pairs or tuples, not just a single column. For example, count distinct (customer, product) pairs where the order was a gift. You can concatenate columns inside the CASE:

SELECT COUNT(DISTINCT CASE WHEN is_gift = TRUE THEN customer_id || '-' || product_id END) AS gift_pairs
FROM order_items;

This works in PostgreSQL and SQLite (using ||). In SQL Server, use CONCAT(customer_id, '-', product_id); in MySQL, CONCAT(customer_id, '-', product_id). Be careful with NULLs: if either column is NULL, the concatenation becomes NULL, and that row is excluded. If you want to include NULLs as a distinct value, you’d need a different approach, like using a subquery with SELECT DISTINCT.

Multiple Conditions: Nested CASE or AND/OR

You can put multiple conditions inside a single CASE using AND/OR, or you can nest CASE expressions. For instance, count distinct customers who are either from the US or have spent over $500:

SELECT COUNT(DISTINCT CASE WHEN country = 'US' OR amount > 500 THEN customer_id END) AS us_or_big_spenders
FROM orders;

If you need different counts for different conditions, use separate CASE expressions in separate columns. For example, count distinct customers per region in one query:

SELECT
  COUNT(DISTINCT CASE WHEN region = 'North' THEN customer_id END) AS north_customers,
  COUNT(DISTINCT CASE WHEN region = 'South' THEN customer_id END) AS south_customers
FROM orders;

Common Mistakes and Pitfalls

  • Forgetting ELSE NULL – If you write CASE WHEN cond THEN col ELSE col END, then every row returns a non-NULL value, so COUNT(DISTINCT) counts all distinct values, ignoring the condition. Always omit ELSE or set it to NULL.
  • Using COUNT(CASE WHEN …) without DISTINCT – That counts rows, not unique values. If the same customer appears twice, you get 2 instead of 1.
  • NULL in the counted column – COUNT(DISTINCT) ignores NULLs. If you need to count NULL as a distinct value, you must use a workaround like COUNT(DISTINCT COALESCE(col, 'NULL_PLACEHOLDER')).
  • Performance on large tables – COUNT(DISTINCT) is expensive because the database must sort or hash all values. Adding CASE doesn’t change that. If you’re counting distinct over millions of rows, consider pre-aggregating with a subquery or using an indexed column.

Alternatives: Subqueries and Window Functions

Sometimes a subquery is clearer. For example, to count distinct customers who ordered in each month, you could write:

SELECT order_month, COUNT(DISTINCT customer_id) AS customers
FROM (SELECT customer_id, DATE_TRUNC('month', order_date) AS order_month FROM orders) t
GROUP BY order_month;

That’s the same as using CASE with GROUP BY, but the subquery makes the logic explicit. In databases that support it, you can also use COUNT(DISTINCT ...) FILTER (WHERE ...) – that’s PostgreSQL and SQLite syntax, which is often more readable:

SELECT COUNT(DISTINCT customer_id) FILTER (WHERE order_date >= '2024-01-01') AS customers_2024 FROM orders;

SQL Server and Oracle don’t support FILTER, so CASE is the portable choice. Another alternative is to use SUM(CASE WHEN ... THEN 1 ELSE 0 END) but that counts rows, not distinct values – only use it if you know each value appears at most once per group.

Performance Considerations and Indexing

Counting distinct values requires the database to eliminate duplicates, which typically involves sorting or hashing. Adding a CASE condition doesn’t change that complexity, but it can reduce the number of rows processed if the condition filters out many rows early. However, the database still scans all rows to evaluate the CASE. If you’re working with large tables, consider these tips:

  • Use a WHERE clause to pre-filter rows before the COUNT, if the condition is the same for all counts.
  • Create an index on the column you’re counting distinct, plus any columns used in the CASE condition. For example, an index on (customer_id, order_date) can help.
  • In PostgreSQL, COUNT(DISTINCT) can use an index-only scan if the indexed column is the one being counted.
  • Avoid wrapping columns in functions inside the CASE (e.g., UPPER(email)) because that prevents index usage.

Frequently Asked Questions

Can I use CASE WHEN with COUNT DISTINCT in MySQL? Yes, MySQL supports this exact syntax: COUNT(DISTINCT CASE WHEN condition THEN column END). It works the same as in other databases. Just be aware that MySQL’s optimizer may not always use indexes efficiently for COUNT(DISTINCT) on large tables.

What’s the difference between COUNT(DISTINCT CASE…) and COUNT(CASE…)? The first counts unique values; the second counts rows. For example, if you have 10 orders from 3 distinct customers, COUNT(DISTINCT customer_id) returns 3, while COUNT(customer_id) returns 10. The CASE version applies the condition before counting, but the same distinction holds.

Does COUNT(DISTINCT) include NULL values? No. By default, COUNT(DISTINCT) ignores NULLs. If you need to count NULL as a distinct value, use COUNT(DISTINCT COALESCE(column, 'some_sentinel')) but be careful that the sentinel doesn’t collide with real values.

Can I use CASE WHEN with COUNT DISTINCT in a GROUP BY query? Absolutely. For example, SELECT region, COUNT(DISTINCT CASE WHEN amount > 100 THEN customer_id END) AS high_value_customers FROM orders GROUP BY region; gives you per-region counts.

Is there a performance difference between CASE and FILTER? In PostgreSQL, FILTER is often optimized better than CASE because it’s a dedicated clause. In other databases, CASE is the only option. For most queries, the difference is negligible unless you’re processing billions of rows.

How do I count distinct values across multiple columns? Use concatenation: COUNT(DISTINCT col1 || '-' || col2) in PostgreSQL/SQLite, CONCAT(col1, '-', col2) in MySQL/SQL Server. This counts unique combinations. Be mindful of NULLs – if either column is NULL, the combination is NULL and excluded.

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.