To count distinct values in SQL, use COUNT(DISTINCT column_name) in a SELECT statement, which returns the number of unique non-NULL values in that column. For example, SELECT COUNT(DISTINCT country) FROM customers; gives the total number of different countries in the customers table.
What COUNT(DISTINCT) Actually Does
SQL’s COUNT() aggregate function counts rows. When you add the DISTINCT keyword inside the parentheses, it first eliminates duplicate values in the specified column (or combination of columns) and then counts the remaining unique rows. Importantly, COUNT(DISTINCT column) ignores NULL values—if a column contains NULL, that row is not counted. This is different from COUNT(*), which counts every row including those with NULLs.
Example: In a table orders with a customer_id column, SELECT COUNT(DISTINCT customer_id) FROM orders; returns the number of unique customers who have placed at least one order. If a customer has 10 orders, they are counted once.
Syntax and Placement
The basic syntax is:
SELECT COUNT(DISTINCT column_name) FROM table_name;
You can also count distinct combinations of multiple columns by listing them separated by commas inside the parentheses:
SELECT COUNT(DISTINCT column1, column2) FROM table_name;
This counts unique pairs of values from both columns. For instance, COUNT(DISTINCT city, state) counts distinct city–state combinations, which is useful when city names repeat across states.
Note: In some database systems (like MySQL), COUNT(DISTINCT expr1, expr2) is supported. In others (like older SQL Server versions), you may need to use a subquery or concatenate values. Always check your database documentation.
Using COUNT(DISTINCT) with GROUP BY
Often you want distinct counts per group. Combine COUNT(DISTINCT ...) with GROUP BY to get per-category unique counts. For example, to count unique products per category:
SELECT category, COUNT(DISTINCT product_id) AS unique_products
FROM products
GROUP BY category;
This returns one row per category with the number of distinct product IDs in that category. The AS keyword gives the result column a clear name.
Performance Considerations
Counting distinct values can be resource-intensive, especially on large tables, because the database must scan all rows and maintain a set of seen values. The cost grows with the number of distinct values and the size of the column data. Here are tips to improve performance:
- Add an index on the column you are counting distinct. An index can help the database skip full table scans in some cases, though for truly distinct counts it still may need to read the index.
- If you only need an approximate count (e.g., for dashboards), some databases offer
APPROX_COUNT_DISTINCT(SQL Server, BigQuery) orCOUNT(DISTINCT ...)with probabilistic algorithms (PostgreSQL’sCOUNT(DISTINCT)is exact, but you can use extensions likeHyperLogLog). - Filter rows early with a
WHEREclause to reduce the dataset before counting. - For very large tables, consider pre-aggregating distinct counts in a summary table if real-time accuracy is not required.
Common Pitfalls and Misconceptions
One common mistake is assuming COUNT(DISTINCT col) counts NULLs. It does not. If you need to count NULLs as a distinct value, you must handle them explicitly, for example by using COALESCE to replace NULL with a placeholder:
SELECT COUNT(DISTINCT COALESCE(column_name, 'UNKNOWN')) FROM table_name;
Another pitfall is using COUNT(DISTINCT *)—this is invalid in most databases. You must specify a column or expression.
Also, COUNT(DISTINCT column) counts distinct non-NULL values, but if the column has trailing spaces or case differences, ‘Apple’ and ‘apple’ are treated as different. Use functions like LOWER() or TRIM() if you need case-insensitive or whitespace-insensitive counts.
Alternatives to COUNT(DISTINCT)
In some situations, you might not need an exact distinct count. Alternatives include:
DISTINCTwithCOUNT()in a subquery:SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS sub;This is equivalent but sometimes clearer.- Window functions: If you need a running distinct count or distinct counts per partition, you can use
COUNT(DISTINCT ...) OVER (PARTITION BY ...)in databases that support it (e.g., PostgreSQL, SQL Server, Oracle). - Approximate functions: As mentioned,
APPROX_COUNT_DISTINCTin SQL Server and BigQuery gives a fast, memory-efficient approximation with a small error margin.
Frequently Asked Questions
Can I use COUNT(DISTINCT) with multiple columns? Yes, in many databases you can write COUNT(DISTINCT col1, col2) to count unique pairs. If your database doesn’t support that, use a subquery with SELECT DISTINCT and then count the rows.
Does COUNT(DISTINCT) include NULL? No, NULL values are ignored. If you want to count NULL as a distinct value, use COALESCE to replace NULL with a non-null placeholder.
What is the difference between COUNT(DISTINCT col) and COUNT(col)? COUNT(col) counts all non-NULL values, including duplicates. COUNT(DISTINCT col) counts only unique non-NULL values.
Why is COUNT(DISTINCT) slow on big tables? Because the database must scan all rows and keep a set of unique values in memory or on disk. Indexes help, but for exact counts on huge datasets, consider approximate methods or pre-aggregation.
Can I use COUNT(DISTINCT) with a WHERE clause? Yes, you can filter rows before counting: SELECT COUNT(DISTINCT col) FROM table WHERE condition;
Is COUNT(DISTINCT) supported in all SQL databases? It is part of the SQL standard and supported by MySQL, PostgreSQL, SQL Server, Oracle, SQLite, and most others. Syntax for multiple columns may vary, so check your database’s documentation.
Related
- How to Create Shortcut Keys in Windows
- Google Sheets COUNTIF Case Sensitive? Exact Match
- Are Random Number Generators Truly Random?
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 Set Enum Value in Java (with Code Examples)In Java, an enum is a special class that represents a fixed set of constants. Setting an enum…
- Excel Calendar Template for Content PlanningYes, you can build a content planning calendar in Excel using a simple grid layout with columns for…
- Excel Not Highlighting Selected Cell? Causes and FixesExcel normally marks the active cell with a colored border; when you select several cells, the rest of…
- Outlook 365 Signature: How to Create and Set It UpTo create a signature in Outlook 365, open the signature settings for the Outlook version you use, add…
- How to Make a Small Booklet in Microsoft WordTo make a small booklet in Microsoft Word, open the Page Setup options, choose the Book fold layout,…
- Monthly Budget Template Excel South Africa: Setup GuideTo make a monthly budget template in Excel for South Africa, create columns for income, planned expenses and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.