To count distinct combinations of values across multiple columns in SQL, use COUNT(DISTINCT col1 || '|' || col2) in most databases, or simply write SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 FROM table) AS sub for a portable approach. The first method concatenates columns into a single string, while the second counts rows from a subquery that already removes duplicates.
Why COUNT(DISTINCT col1, col2) Fails
Standard SQL does not allow multiple arguments inside COUNT(DISTINCT ...). If you try COUNT(DISTINCT col1, col2), most databases throw a syntax error. This is a common frustration because people naturally expect it to work like GROUP BY col1, col2. The SQL standard defines COUNT(DISTINCT expr) with only one expression, so database vendors have not implemented multi-argument versions (with a few exceptions like some versions of PostgreSQL and SQL Server, but even those are not standard and behave differently).
The Concatenation Method
The most direct workaround is to combine the columns into a single value before counting. For example, to count distinct (city, state) pairs from a customers table:
SELECT COUNT(DISTINCT city || '|' || state) AS distinct_locations
FROM customers;
Here, || is the string concatenation operator in standard SQL, PostgreSQL, and SQLite. In MySQL and MariaDB, use CONCAT(city, '|', state) instead. In SQL Server, use CONCAT(city, '|', state) or the older city + '|' + state.
Choose a separator (like '|') that does not appear in the column values. If a city name could contain a pipe, pick a different delimiter or use a more robust approach like CONCAT_WS (MySQL) or CONCAT_WS (PostgreSQL 9.1+).
The Subquery Method (Most Portable)
If you want a solution that works across all databases without worrying about concatenation quirks, use a subquery:
SELECT COUNT(*) AS distinct_pairs
FROM (SELECT DISTINCT city, state FROM customers) AS sub;
This first creates a distinct set of (city, state) pairs, then counts the rows in that set. It is clear, standard, and avoids any delimiter issues. The performance is usually fine for moderate-sized tables, though the concatenation method can be faster in some engines because it avoids a derived table.
Using GROUP BY with COUNT
Sometimes you do not need a single count; you want the count of each distinct combination. That is what GROUP BY does:
SELECT city, state, COUNT(*) AS occurrences
FROM customers
GROUP BY city, state;
This returns one row per distinct (city, state) pair, with the number of times that pair appears. If you only need the number of distinct pairs, you can wrap this in a subquery and count the rows:
SELECT COUNT(*) FROM (SELECT city, state FROM customers GROUP BY city, state) AS sub;
Note that GROUP BY also collapses NULLs into a single group, whereas DISTINCT treats NULLs as equal too. So both methods handle NULLs the same way: all NULLs in a column are considered one distinct value.
Handling NULLs Correctly
Be careful with NULLs. In SQL, COUNT(DISTINCT col) ignores NULLs entirely. But when you concatenate columns, a NULL in any column makes the entire concatenated string NULL, and that NULL is then ignored. This means the concatenation method silently drops rows where any column is NULL. The subquery method, however, treats NULLs as a distinct value (because DISTINCT treats NULLs as equal to each other).
Example: if you have a row with (city=’London’, state=NULL), the concatenation method will not count it at all. The subquery method will count it as one distinct combination (London, NULL). To match the behavior of ignoring NULLs, you can add a WHERE clause to exclude NULLs:
SELECT COUNT(*) FROM (SELECT DISTINCT city, state FROM customers WHERE city IS NOT NULL AND state IS NOT NULL) AS sub;
Decide which behavior you want before choosing a method.
Database-Specific Functions
Some databases offer shortcuts:
- PostgreSQL supports
COUNT(DISTINCT (col1, col2))using a row constructor, but it treats the pair as a composite type, which may not behave as expected with NULLs. - SQL Server has
COUNT(DISTINCT col1 + '|' + col2)but requires converting non-string columns to strings first. - MySQL does not support multiple arguments in
COUNT(DISTINCT); useCONCAT. - Oracle does not support multiple arguments either; use concatenation with
||. - SQLite supports
COUNT(DISTINCT col1 || '|' || col2).
Always test with your specific database version, as behavior can change.
Performance Considerations
Counting distinct combinations can be expensive on large tables because the database must sort or hash all rows to find duplicates. The concatenation method often uses less memory than a subquery because it avoids materializing a derived table, but it may still need to sort the concatenated strings. The subquery method may benefit from an index on the columns involved, but the DISTINCT operation itself is the bottleneck.
For very large datasets, consider pre-aggregating with GROUP BY and storing the results in a summary table, or using a window function if you need running counts. Also, be aware that concatenating many columns can create very long strings, which might exceed limits (e.g., 8000 bytes in SQL Server for VARCHAR).
Frequently Asked Questions
Can I use COUNT(DISTINCT col1, col2) in MySQL?
No, MySQL does not support multiple arguments in COUNT(DISTINCT). Use COUNT(DISTINCT CONCAT(col1, '|', col2)) or the subquery method.
How do I count distinct combinations of 3 or more columns?
Use the same approaches: concatenate all columns with a delimiter, or use a subquery with SELECT DISTINCT col1, col2, col3. For example: SELECT COUNT(*) FROM (SELECT DISTINCT a, b, c FROM t) AS sub;
Does COUNT(DISTINCT) ignore NULLs in multiple columns?
Yes, COUNT(DISTINCT col) ignores NULLs. When you concatenate, if any column is NULL, the result is NULL and is ignored. The subquery method counts NULL as a distinct value unless you filter them out.
What is the fastest way to count distinct multiple columns?
It depends on your database and data distribution. The concatenation method is often faster because it avoids a derived table, but it can slow down if concatenation is expensive or if the strings are long. Test both on your data.
Can I use GROUP BY to count distinct combinations?
Yes, GROUP BY col1, col2 gives you each combination and its count. To get the total number of combinations, wrap it in a subquery and count rows.
Why does my COUNT(DISTINCT) return 0 when there are rows?
If all values in the concatenated string are NULL (because all columns are NULL for every row), COUNT returns 0. Also, if you filter with a WHERE clause that excludes all rows, you get 0. Check your data and conditions.
Related
- SQL COUNT DISTINCT Values: Syntax & Examples
- Selected Cell How Many Minutes? Excel Time Guide
- Entry Level Data Entry: Real Jobs, Pay, Skills
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Create an Outlook Signature on an HP LaptopTo create an Outlook signature on an HP laptop, open Outlook, go to its signature settings, write and…
- Out of Office in New Outlook: Set It Up and Schedule ItTo set up an out-of-office reply in New Outlook, open Settings, go to Accounts > Automatic replies, choose…
- Add a Shared Mailbox in Legacy Outlook for MacTo add a shared mailbox in legacy Outlook for Mac, open Tools > Accounts, select your Exchange account,…
- Excel Merge Cells: How to Combine Cells in ExcelYes, Excel can merge cells. To merge cells in Microsoft Excel, select the cells you want to combine,…
- How to Copy Text With Track Changes in Microsoft WordTo copy text with its existing tracked edits, show all markup in the source document, select the passage,…
- Auto Sum Shortcut in Excel: Quick Keys & StepsThe fastest way to sum a column or row in Excel is to press Alt + = (Windows)…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.