To count unique values in SQL, use COUNT(DISTINCT column_name) in a SELECT statement, which returns the number of distinct non-NULL values in that column. For example, SELECT COUNT(DISTINCT country) FROM customers; counts how many different countries appear in the customers table.
What Does “Unique” Mean in SQL?
In SQL, “unique” can mean two different things, and it’s important to distinguish them:
- Distinct values – the set of different values that appear in a column, ignoring duplicates. Counting distinct values answers “how many different categories exist?”
- Unique rows – rows that appear only once in the table (no duplicate rows). Counting these answers “how many rows have no exact duplicate?”
Most people asking about counting unique values actually want the number of distinct values. The COUNT(DISTINCT ...) function handles that directly. If you need the count of rows that appear exactly once, you’d use a subquery with GROUP BY and HAVING COUNT(*) = 1.
Basic COUNT(DISTINCT) Syntax
The core syntax is straightforward:
SELECT COUNT(DISTINCT column_name) FROM table_name;
For example, given a table orders with columns customer_id and product_id, you can count how many distinct customers placed orders:
SELECT COUNT(DISTINCT customer_id) FROM orders;
This ignores NULL values automatically. If a column contains NULL, COUNT(DISTINCT column) does not count NULL as a value. To include NULL as a distinct value (if needed), you’d need a workaround like COUNT(DISTINCT COALESCE(column, 'NULL_PLACEHOLDER')).
Counting Unique Values Across Multiple Columns
Sometimes you need to count unique combinations of two or more columns. For instance, how many distinct (customer, product) pairs exist in the orders table? You can use concatenation:
SELECT COUNT(DISTINCT customer_id || '-' || product_id) FROM orders;
But be careful: if the separator character appears in the data, you might get false collisions. A safer approach is to use a subquery with SELECT DISTINCT:
SELECT COUNT(*) FROM (SELECT DISTINCT customer_id, product_id FROM orders) AS sub;
This counts every unique combination of the two columns. The subquery returns one row per distinct pair, and the outer COUNT(*) counts those rows.
Using GROUP BY to Get Counts per Unique Value
If you want not just the total number of unique values, but also how many times each value appears, use GROUP BY:
SELECT country, COUNT(*) AS cnt FROM customers GROUP BY country;
This returns one row per distinct country with the number of customers in that country. To see only countries with more than one customer, add HAVING COUNT(*) > 1.
To get the number of distinct countries along with the total rows, you can combine both in one query:
SELECT COUNT(DISTINCT country) AS unique_countries, COUNT(*) AS total_rows FROM customers;
Performance and Large Data Sets
Counting distinct values can be expensive on large tables because the database must scan all rows and keep a set of seen values in memory or on disk. For millions of rows, COUNT(DISTINCT ...) may be slow. Some tips:
- Add an index on the column(s) you’re counting distinct over. An index can help the database skip duplicates more efficiently, though it’s not always used for distinct counts.
- If you only need an approximate count (e.g., for dashboards), some databases offer approximate functions like
APPROX_COUNT_DISTINCT(BigQuery, SQL Server) orHLL_COUNT(PostgreSQL with extension). These are much faster but return an estimate. - For very large tables, consider pre-aggregating counts in a summary table that you maintain with triggers or scheduled jobs.
Common Pitfalls and Misconceptions
One common mistake is using COUNT(column) expecting it to count unique values – it doesn’t; it counts non-NULL values including duplicates. Another is forgetting that COUNT(DISTINCT) ignores NULLs, which might surprise you if your column has many NULLs.
Another misconception: SELECT DISTINCT and GROUP BY are often interchangeable for listing unique values, but they differ in that GROUP BY allows aggregation. For just counting, COUNT(DISTINCT) is the cleanest.
Also note that in some SQL dialects (like MySQL), COUNT(DISTINCT) can take multiple arguments: COUNT(DISTINCT col1, col2) counts distinct pairs. But this is not standard SQL; in PostgreSQL, for example, you’d use the subquery method.
Alternatives: Window Functions and Subqueries
If you need to count unique values per group while also showing detail rows, window functions come in handy. For instance, to show each order with the number of distinct customers per region:
SELECT order_id, region, COUNT(DISTINCT customer_id) OVER (PARTITION BY region) AS region_unique_customers FROM orders;
This adds a column to every row showing the distinct customer count for that region. Note that COUNT(DISTINCT ...) OVER (...) is supported in PostgreSQL, SQL Server, and Oracle, but not in MySQL (as of MySQL 8.0, it’s still not supported). In MySQL, you’d need a correlated subquery or a join.
Another alternative for counting unique values is to use a subquery with GROUP BY and then count the rows:
SELECT COUNT(*) FROM (SELECT customer_id FROM orders GROUP BY customer_id) AS t;
This is essentially the same as COUNT(DISTINCT customer_id) but can be more flexible if you want to add conditions in the subquery.
Frequently Asked Questions
How do I count unique values with a WHERE condition?
Just add a WHERE clause before the COUNT. For example, to count distinct countries of customers who have made a purchase: SELECT COUNT(DISTINCT country) FROM customers WHERE purchase_count > 0; The WHERE filters rows first, then the distinct count applies to the filtered set.
What’s the difference between COUNT(*) and COUNT(DISTINCT column)?
COUNT(*) counts all rows in the result set, including duplicates and NULLs. COUNT(DISTINCT column) counts only the number of different non-NULL values in that column. So if you have 100 rows but only 5 different countries, COUNT(*) returns 100 and COUNT(DISTINCT country) returns 5.
Can I count unique values across multiple columns at once?
Yes, but the method depends on your database. In MySQL, you can use COUNT(DISTINCT col1, col2) directly. In PostgreSQL, SQL Server, and others, use a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 FROM table) AS t; This counts unique combinations.
Why does COUNT(DISTINCT) ignore NULL values?
Because NULL represents an unknown or missing value, and treating all NULLs as the same would be misleading. If you need to count NULL as a distinct value, you can use COUNT(DISTINCT COALESCE(column, 'NULL')) but be careful with data collisions.
How can I count unique values in a text column with case differences?
Standard SQL treats ‘Apple’ and ‘apple’ as different values. To count case-insensitively, convert to a common case: SELECT COUNT(DISTINCT LOWER(column)) FROM table; This counts ‘apple’ once regardless of original case.
Related
- Google Sheets Conditional Formatting Formula Guide
- Albuquerque Traffic Light Cameras: How They Work
- Fed Funds Balance Sheet: What It Is & How It Works
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel GROUPBY With Multiple Criteria: Filter ArraysTo group Excel data while applying multiple row-level criteria, use the filter_array argument in GROUPBY and combine AND…
- Randomize Cells in Excel: Formulas, Steps, and TipsYes. In Excel for Microsoft 365 on Windows, you can randomize a list with a formula such as…
- Create Function in Snowflake: SQL & Python UDFsTo create a function in Snowflake, you use the CREATE FUNCTION command, which defines a user-defined function (UDF)…
- SUMPRODUCT in Excel: How Its Array Calculations WorkIn Excel, SUMPRODUCT multiplies corresponding values in one or more arrays and adds the resulting products. It is…
- Excel Sort and Filter Shortcuts: A Practical GuideIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to turn filter buttons on or off for a…
- String Operations and Functions in PythonString operations and functions in Python let you manipulate text using built-in methods like split(), join(), replace(), and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.