Unique Values by Count: SQL, Excel & Data Tools
Unique values by count means the number of distinct entries in a dataset column, ignoring duplicates. For example, in a list of 100 customer names with 20 repeats, the unique count is 80. This article explains how to calculate unique counts in SQL, Excel, Google Sheets, and Python, and how to interpret the results correctly.
Why Unique Counts Matter
Counting unique values is a fundamental data analysis task. It answers questions like: How many distinct products did we sell? How many unique visitors came to the site? How many different error codes appeared in the logs? Knowing the unique count helps you understand the diversity of your data, spot data quality issues, and make better business decisions.
A common mistake is confusing unique count with total count. Total count includes every row; unique count only includes each distinct value once. For instance, a table of 1,000 orders might have only 500 unique customer IDs because each customer ordered twice on average.
Counting Unique Values in SQL
In SQL, the standard way to count unique values is with COUNT(DISTINCT column_name).
- Basic syntax:
SELECT COUNT(DISTINCT customer_id) FROM orders;– returns the number of unique customer IDs. - Multiple columns:
SELECT COUNT(DISTINCT city, state) FROM customers;– counts unique combinations of city and state (supported in most databases like PostgreSQL, SQLite, and MySQL 8.0+). - With conditions:
SELECT COUNT(DISTINCT product_id) FROM sales WHERE sale_date > '2024-01-01';– counts unique products sold after a certain date.
If your database doesn’t support COUNT(DISTINCT) with multiple columns, you can concatenate them: COUNT(DISTINCT city || '|' || state).
Counting Unique Values in Excel and Google Sheets
In Excel, the COUNTIF function can be used to count occurrences, but for unique counts you need SUMPRODUCT or the newer UNIQUE function (Excel 365 and Google Sheets).
- Excel 365 / Google Sheets:
=COUNTA(UNIQUE(A2:A100))– returns the number of unique values in the range. UseCOUNTAfor text,COUNTfor numbers only. - Older Excel:
=SUMPRODUCT(1/COUNTIF(A2:A100, A2:A100))– works but can be slow on large ranges and fails if there are blank cells (dividing by zero). - Pivot Table: Add the field to the Rows area, then right-click and select “Value Field Settings” → “Distinct Count” (available in Excel 2013 and later).
In Google Sheets, you can also use =COUNTUNIQUE(A2:A100) which is simpler and ignores blank cells.
Counting Unique Values in Python and R
For programmers, counting unique values is straightforward.
- Python (pandas):
df['column'].nunique()– returns the number of unique values. Adddropna=Falseto include NaN as a unique value. - Python (pure):
len(set(my_list))– works for any list of hashable items. - R:
length(unique(df$column))– orn_distinct(df$column)from dplyr.
These methods are efficient for medium-sized datasets. For very large data, consider using database queries or specialized tools like Apache Spark.
How to Choose the Right Method
Your choice depends on your data size and tool availability.
- Small data (under 10,000 rows): Excel or Google Sheets is fine. Use
UNIQUEorCOUNTUNIQUE. - Medium data (10,000 to 1 million rows): SQL or Python pandas works well. SQL is often faster if the data is already in a database.
- Large data (millions of rows): Use a database with proper indexing or a distributed system like Spark. Avoid loading everything into Excel.
Also consider whether you need the actual unique values or just the count. If you need the values, use SELECT DISTINCT or UNIQUE().
Common Problems and Misconceptions
Several issues trip up users when counting unique values.
- Blank cells: In Excel,
COUNTIFbased formulas can return errors if blanks exist. UseCOUNTUNIQUEin Google Sheets which ignores blanks, or filter out blanks first. - Case sensitivity: SQL’s
COUNT(DISTINCT)is case-sensitive in PostgreSQL but case-insensitive in MySQL by default. Excel’sUNIQUEis case-insensitive. Be aware of this when comparing results. - Trailing spaces: ‘apple’ and ‘apple ‘ are different values. Clean your data with
TRIM()before counting. - Numbers vs text: 1 and ‘1’ are different in most systems. Ensure consistent data types.
A common misconception is that COUNT(DISTINCT) is slow and should be avoided. In modern databases, it’s optimized and often the best choice. For huge datasets, consider using a hyperloglog approximation (e.g., COUNT(DISTINCT) in Redshift or BigQuery) which gives approximate counts for speed.
Comparing Unique Counts Across Groups
Often you need unique counts per category. In SQL, use GROUP BY:
SELECT category, COUNT(DISTINCT product_id) AS unique_products FROM sales GROUP BY category;
In Excel, use a Pivot Table with the category in Rows and the product ID in Values, then set it to “Distinct Count”. In Python, use df.groupby('category')['product_id'].nunique().
This is useful for comparing diversity across segments, like unique customers per region or unique error codes per server.
Frequently Asked Questions
What is the difference between unique and distinct?
In everyday language, they are synonyms. In databases, “distinct” is the keyword used to return unique rows. “Unique” is often used to describe a column with no duplicates (a unique constraint). When counting, both refer to the same concept: each value counted once.
Why does my COUNT(DISTINCT) return a different number than Excel?
Possible reasons: case sensitivity differences (PostgreSQL vs Excel), trailing spaces, or different handling of blank cells. Also, Excel’s COUNTIF method can be inaccurate if there are blank cells. Use UNIQUE or COUNTUNIQUE for more reliable results.
Can I count unique values with multiple conditions?
Yes. In SQL, add a WHERE clause. In Excel, use COUNTIFS with the SUMPRODUCT method, or use a Pivot Table with filters. In Python, filter the DataFrame first: df[df['date'] > '2024-01-01']['product'].nunique().
How do I count unique values ignoring blanks?
In Google Sheets, COUNTUNIQUE ignores blanks. In Excel, COUNTA(UNIQUE(range)) ignores blanks because UNIQUE returns only non-empty values. In SQL, COUNT(DISTINCT) ignores NULLs by default. In Python, nunique(dropna=True) is the default.
What is an approximate unique count?
Some databases like BigQuery and Redshift offer APPROX_COUNT_DISTINCT which uses a hyperloglog algorithm to estimate the count very quickly, with a small error (usually under 2%). It’s useful for huge datasets where exact counts are too slow.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.