To count unique values in a SQL column, use COUNT(DISTINCT column_name) in a SELECT query. For example, SELECT COUNT(DISTINCT country) FROM customers; returns the number of distinct countries. This method works in most SQL databases, though some (like MySQL) also offer alternative syntaxes.
What Does “Unique Values” Mean in SQL?
In SQL, “unique values” refers to the distinct entries in a column, ignoring duplicates. For instance, if a column contains ‘red’, ‘blue’, ‘red’, ‘green’, the unique values are ‘red’, ‘blue’, ‘green’—so the count is 3. This is different from counting all rows (which would be 4) or counting non-null values (which would also be 4 if no nulls).
NULL values are typically not counted in COUNT(DISTINCT column). If you need to include NULL as a distinct value, you’ll need a workaround, like using COUNT(DISTINCT COALESCE(column, 'NULL_PLACEHOLDER')), but this is rarely needed.
How COUNT(DISTINCT) Works
The COUNT(DISTINCT column) function scans the specified column, removes duplicate values, and returns the number of remaining values. It’s a combination of the DISTINCT keyword and the COUNT aggregate function.
Here’s a basic example with a table named orders:
-- Assume orders table has a column 'status' with values: 'shipped', 'pending', 'shipped', 'cancelled', 'pending'
SELECT COUNT(DISTINCT status) AS unique_statuses FROM orders;
-- Returns 3
You can also use it with a WHERE clause to filter rows before counting:
SELECT COUNT(DISTINCT customer_id) FROM orders WHERE order_date > '2024-01-01';
This counts distinct customers who placed orders after January 1, 2024.
Alternative Methods: GROUP BY and Subqueries
Sometimes you need more than just the count—you might want the actual unique values or a count per group. For that, use GROUP BY:
SELECT status, COUNT(*) FROM orders GROUP BY status;
-- Returns each status and how many times it appears
To get the number of unique values per group, combine GROUP BY with COUNT(DISTINCT):
SELECT category, COUNT(DISTINCT product_id) FROM products GROUP BY category;
If you need the count of unique values from a subquery (e.g., after deduplicating rows), you can do:
SELECT COUNT(*) FROM (SELECT DISTINCT column FROM table) AS sub;
This is equivalent to COUNT(DISTINCT column) in most cases, but can be useful when you need to apply additional logic like filtering after deduplication.
Performance Considerations and Indexes
Counting distinct values can be resource-intensive on large tables because the database must scan and sort or hash all values to identify duplicates. Here are a few tips:
- An index on the column can speed up
COUNT(DISTINCT)in some databases, but not all—test your specific DBMS. - For very large tables, consider using an approximate count if precision isn’t critical. For example, PostgreSQL has
COUNT(DISTINCT)as exact, but you can useAPPROX_COUNT_DISTINCTin SQL Server orHLLfunctions in BigQuery. - If you frequently need this count, consider maintaining a summary table that updates on insert/delete.
Be aware that COUNT(DISTINCT) can be slow on columns with high cardinality (many unique values) because the database must process each distinct value.
Database-Specific Variations
While COUNT(DISTINCT) is standard SQL, some databases offer alternatives:
- MySQL and MariaDB: Support
COUNT(DISTINCT)directly. Also,COUNT(DISTINCT col1, col2)counts distinct combinations. - PostgreSQL: Supports
COUNT(DISTINCT)and alsoCOUNT(DISTINCT (col1, col2))for multiple columns. - SQL Server: Supports
COUNT(DISTINCT). For approximate counts, useAPPROX_COUNT_DISTINCT(available from 2019). - Oracle: Supports
COUNT(DISTINCT). Also,COUNT(DISTINCT col1 || col2)for concatenated values. - SQLite: Supports
COUNT(DISTINCT).
For counting distinct combinations of multiple columns, the syntax varies. In standard SQL, you can use COUNT(DISTINCT col1 || '-' || col2) but that can be error-prone. Better to use a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 FROM table) t;
Common Mistakes and How to Avoid Them
Here are frequent pitfalls when counting unique values:
- Counting NULLs: Remember that
COUNT(DISTINCT col)ignores NULLs. If you need to include NULL as a value, useCOUNT(DISTINCT COALESCE(col, 'NULL')). - Using
DISTINCTwithCOUNT(*)incorrectly:COUNT(DISTINCT *)is invalid. You must specify a column or expression. - Forgetting to handle case sensitivity: In some databases, ‘Apple’ and ‘apple’ are considered different. If you need case-insensitive counting, use
COUNT(DISTINCT LOWER(col)). - Assuming
COUNT(DISTINCT)counts non-null values: It counts distinct non-null values, not all non-null values. For all non-null, useCOUNT(col).
Frequently Asked Questions
How do I count unique values in a column with NULLs?
By default, COUNT(DISTINCT col) ignores NULLs. If you want to count NULL as a unique value, use COUNT(DISTINCT COALESCE(col, 'NULL')) but be careful not to collide with actual ‘NULL’ strings. Alternatively, you can add a separate count of NULLs: SELECT COUNT(DISTINCT col) + SUM(CASE WHEN col IS NULL THEN 1 ELSE 0 END) FROM table;
Can I count unique values across multiple columns?
Yes, you can count distinct combinations of multiple columns. In MySQL and PostgreSQL, use COUNT(DISTINCT col1, col2). In SQL Server and Oracle, use a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 FROM table) t;
Why is COUNT(DISTINCT) slow on my large table?
Because the database must sort or hash all values to find duplicates. If you have an index on the column, it may help, but not always. For very large tables, consider using an approximate count function like APPROX_COUNT_DISTINCT (SQL Server) or HLL_COUNT (BigQuery), or maintain a summary table.
What is the difference between COUNT(DISTINCT col) and COUNT(col)?
COUNT(DISTINCT col) returns the number of unique non-null values. COUNT(col) returns the number of non-null values (including duplicates). For example, if col has values ‘a’, ‘a’, ‘b’, NULL, COUNT(DISTINCT col) returns 2, while COUNT(col) returns 3.
How do I count unique values per group?
Use GROUP BY with COUNT(DISTINCT). For example: SELECT category, COUNT(DISTINCT product_id) FROM products GROUP BY category; This gives the number of distinct products per category.
Related
- Shortcut Command for Cut: Ctrl+X Explained
- Best Data Entry Sites: Top Picks for Real Work
- Kansas City Kansas Traffic Cameras: How They Work
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel String Functions and Operators ExplainedIn Excel, string functions work with text, while operators combine values or compare them. The main text-joining operator…
- Excel Filter Based on Multiple Criteria: How It WorksTo filter Excel data by multiple criteria, use Data > Filter and set a condition in each relevant…
- Excel Only Show Cells with Data? Filter & Hide BlanksNo, Excel does not automatically show only cells with data; you must use filtering, Go To Special, or…
- How to Use SUBTOTAL and SUMIF in ExcelThis guide shows you how to use Excel’s SUBTOTAL and SUMIF functions to summarize data. SUBTOTAL calculates totals…
- COUNTIF 0 in Excel: Count Zero Values and Blank CellsTo count cells that match zero in Excel, use =COUNTIF(A2:A20,0), replacing A2:A20 with your range. Be aware that…
- Concat Excel Multiple Cells: Formulas, Spaces, and TipsTo concat (combine) multiple cells in Excel, use =CONCAT(A2:C2) to join the values in A2 through C2 without…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.