Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

COUNT(DISTINCT) in SQL: A Complete Guide to Counting Unique Values

By Mukesh Kumar

Updated on Feb 27, 2025 | 15 min read

Share:

In SQL, the COUNT function is used to determine the number of rows in a dataset, making it essential for analyzing data. However, when you need to count only unique values in a column, the DISTINCT keyword comes into play. 

By combining COUNT with DISTINCT, you can efficiently retrieve the number of unique records, such as distinct customers, products, or transactions, instead of counting all rows, including duplicates.

This blog explores Count Distinct in SQL, its syntax, practical examples, performance considerations, and best practices for optimizing queries.

Understanding COUNT Function

The COUNT function in SQL is your go-to tool for determining how many rows exist in a table. Whether you’re analyzing sales, tracking users, or summarizing transactions, COUNT helps you quickly quantify data.

Let’s start with a simple example. Say you have a table called orders, and you want to know how many total records it holds:

SELECT COUNT(*) FROM orders;

This query counts all rows in the orders table, regardless of duplicates or empty values. It’s a straightforward way to get a total record count.

COUNT with WHERE Clause

Now, what if you only want to count specific records? That’s where the WHERE clause comes in. Let’s say you want to count only the orders placed in 2025:

SELECT COUNT(*) FROM orders WHERE order_date >= '2025-01-01';

Here, SQL only counts rows where order_date is in 2025. The WHERE clause filters the data before counting, giving you a precise number based on your conditions.

This ability to filter makes COUNT a powerful tool for analyzing subsets of data—like counting active users, pending transactions, or products in stock.

Optimization Tip: If order_date is indexed, the performance will improve.

You can also learn more about SQL concepts with upGrad’s online software development courses. The comprehensive curriculum covers essential SQL concepts, query optimization techniques, and real-world applications.

Also Read: Top 27 SQL Projects in 2025 With Source Code: For All Levels

Now that you know how COUNT works, what if you only want to count unique values? That’s where DISTINCT helps by filtering out duplicates.

The Role of the DISTINCT Keyword in SQL

When working with data, you’ll often come across duplicate values. Maybe you have multiple orders from the same customer, repeated product entries, or duplicate email addresses in a user database. If you need a list of only unique values, that’s where DISTINCT comes in.

The DISTINCT keyword ensures that your query returns only unique values from a specific column. Let’s say you have a table called customers, and you want to find all the unique cities where your customers are located:

SELECT DISTINCT city FROM customers;

Without DISTINCT, if multiple customers live in the same city, you’d get repeated city names in your result. But by using DISTINCT, SQL removes duplicates and returns only one entry per unique city.

So, when should you use DISTINCT? Here are a few common scenarios:

  • Removing Duplicate Customer Entries – If a customer made multiple purchases, but you only need a list of unique customers, DISTINCT ensures each customer appears only once.
  • Finding Unique Product Categories – In an e-commerce database, products may belong to various categories. Using DISTINCT helps identify the different categories available.
  • Extracting Unique Email Addresses – If a system logs user activity and stores emails repeatedly, DISTINCT helps filter out duplicate entries, giving you a clean email list.
  • Analyzing Unique Locations – If you want to see all different cities where your business has customers, DISTINCT ensures each city appears only once in the result.

By eliminating duplicates, DISTINCT helps streamline your data, making your queries more efficient and your reports more accurate.

You can also learn about the more complex applications of SQL with upGrad’s Free Advanced SQL Course. Learn essential functions, formulas, and optimization techniques to write efficient queries.

Also Read: Is SQL Hard to Learn? Challenges, Tips, and Career Insights

You’ve seen how DISTINCT removes duplicates, but what if you need to count those unique values? That’s where COUNT(DISTINCT) comes in.

Combining COUNT with DISTINCT in SQL

Now that you understand both COUNT and DISTINCT, let's put them together. Sometimes, you don’t just want to count all rows—you need to count only unique values. That’s where COUNT(DISTINCT column_name) becomes incredibly useful.

Here’s a simple example of how to count unique values in a column using Count Distinct in SQL:

SELECT COUNT(DISTINCT column_name) FROM table_name;

This query counts the number of distinct (unique) values in a column. Instead of counting all rows, it filters out duplicates before counting.

You’ll use SQL COUNT() with DISTINCT whenever you need to count only unique occurrences. Some common scenarios include:

  • Counting Unique Customers – How many different customers placed orders?
  • Counting Unique Products Sold – How many different products were purchased?
  • Counting Unique Locations – How many cities have sales activity?
  • Counting Unique Employee Departments – How many different departments exist in a company?

Also Read: How to Use SQL for Data Science [Benefits, Skills and Career Opportunities]

Let’s go through two practical examples using Count Distinct in SQL.

Practical Example 1: Using COUNT(DISTINCT) for Fraud Detection in Login Attempts

In an e-commerce platform, fraud detection is critical. One of the ways to identify potential fraudulent behavior is by tracking how many unique IP addresses are used in login attempts for a specific user. 

If a user suddenly logs in from multiple IP addresses in a short period of time, it may indicate suspicious behavior, such as account takeover or unauthorized access attempts.

Scenario: You want to track how many unique IP addresses have been used by each user during their login attempts to identify suspicious activity.

Here's the schema for the login_attempts table:

CREATE TABLE login_attempts (
    attempt_id INT PRIMARY KEY,
    user_id INT,
    ip_address VARCHAR(45),
    attempt_time TIMESTAMP
);

Sample data:

INSERT INTO login_attempts (attempt_id, user_id, ip_address, attempt_time) VALUES
(1, 101, '192.168.1.1', '2024-02-01 08:00:00'),
(2, 101, '192.168.1.2', '2024-02-01 09:00:00'),
(3, 101, '192.168.1.1', '2024-02-01 10:00:00'),
(4, 102, '192.168.1.3', '2024-02-01 11:00:00'),
(5, 102, '192.168.1.3', '2024-02-01 12:00:00'),
(6, 103, '192.168.1.4', '2024-02-01 13:00:00'),
(7, 103, '192.168.1.5', '2024-02-01 14:00:00'),
(8, 103, '192.168.1.5', '2024-02-01 15:00:00');

To identify the number of unique IP addresses used by each user, you can use the COUNT(DISTINCT ip_address) function:

SELECT user_id, COUNT(DISTINCT ip_address) AS unique_ips
FROM login_attempts
GROUP BY user_id;

Expected Output:

user_id

unique_ips

101

2

102

1

103

2

Explanation:

  • User 101 has logged in from two unique IP addresses (192.168.1.1 and 192.168.1.2).
  • User 102 has only used one IP address (192.168.1.3).
  • User 103 has logged in from two unique IP addresses (192.168.1.4 and 192.168.1.5).

This query is useful because it allows you to identify if a user is attempting to log in from multiple locations (potentially indicating account hijacking). 

For example, if user 101 is known to only access the account from a specific region, but logs in from two different IP addresses across distinct geographic locations, you may flag it for further investigation.

Why This is Useful in Fraud Detection:

  • Suspicious Activity: Multiple unique IP addresses within a short time frame could indicate that an account is being accessed from unusual locations, suggesting potential fraud or a compromised account.
  • Risk Mitigation: By monitoring the number of unique IPs, you can implement strategies such as blocking suspicious IPs or requiring additional verification steps (e.g., multi-factor authentication) if the user is logging in from many different locations.
  • Improved User Behavior Analytics: Tracking IPs helps in understanding typical user behavior patterns, so deviations can be flagged in real-time.

Using COUNT(DISTINCT) in this way helps build a reliable system for detecting and preventing unauthorized access or fraudulent activity in real-time.

Practical Example 2: Using COUNT(DISTINCT) for E-commerce Analytics (Counting Unique Users Who Added Items to Cart)

In e-commerce, it's crucial to track customer behavior to understand which products are getting attention and how many different users are interacting with those products. 

One important metric for understanding interest in products is the number of unique users who added an item to their shopping cart.

Scenario: You want to track how many different users have added a specific product to their cart. This can help determine how popular a product is and whether it has the potential to convert into sales.

Here’s the schema for the cart_additions table:

CREATE TABLE cart_additions (
    addition_id INT PRIMARY KEY,
    user_id INT,
    product_id INT,
    addition_date DATE
);

Sample data:

INSERT INTO cart_additions (addition_id, user_id, product_id, addition_date) VALUES
(1, 101, 201, '2024-02-01'),
(2, 102, 202, '2024-02-01'),
(3, 101, 203, '2024-02-01'),
(4, 103, 201, '2024-02-02'),
(5, 104, 204, '2024-02-02'),
(6, 101, 202, '2024-02-03'),
(7, 105, 201, '2024-02-03'),
(8, 106, 202, '2024-02-04');

Query to Count Unique Users Who Added a Specific Product to Cart: Suppose you want to know how many unique users added product 201 to their cart. You can use COUNT(DISTINCT) to ensure you don't double-count users who added the product multiple times:

SELECT COUNT(DISTINCT user_id) AS unique_users_added_product_201
FROM cart_additions
WHERE product_id = 201;

Expected Output:

unique_users_added_product_201

4

Explanation:

  • Product 201 has been added to the cart by users 101, 103, 105, and 107.
  • Even though product 201 was added multiple times (user 101 added it twice), COUNT(DISTINCT) only counts the unique users who added it to their cart, so the total count is 4.

Why This Is Useful in E-Commerce Analytics:

  • Product Popularity: By tracking unique users who add a product to their cart, you can measure the level of interest in a product. A higher number of unique users indicates strong demand.
  • Conversion Potential: If a product has many unique users adding it to their cart but low sales conversion, it might indicate a problem with checkout or payment processes, or it could signal issues with pricing or shipping.
  • Customer Segmentation: By knowing how many unique users are engaging with certain products, you can segment your customer base more effectively for targeted marketing campaigns or special offers.

For example, if you notice a high number of users adding product 201 to their cart but not completing the purchase, you might want to run an analysis on potential drop-off points or even send out a reminder email or offer a discount to encourage those users to finalize their purchase.

Extended Use Case: Comparing Product Interest

You could extend this query to compare how many unique users added multiple products to their cart, helping you understand which products are being viewed the most.

SELECT product_id, COUNT(DISTINCT user_id) AS unique_users_added
FROM cart_additions
GROUP BY product_id
ORDER BY unique_users_added DESC;

Expected Output:

product_id

unique_users_added

201

4

202

3

203

1

204

1

This shows which products are attracting the most attention and which might require more visibility to increase user interaction.

Why This is Valuable:

  • Marketing Focus: Products with higher unique user engagement are likely the ones that deserve more marketing resources.
  • Inventory Planning: Tracking which products are added frequently helps predict demand and optimize inventory levels.

This technique is essential for making data-driven decisions in business analysis, inventory tracking, and customer segmentation.

Also Read: Stored Procedure in SQL: How to Create, Executive, Modify, Types & Use Cases

Advanced Scenarios Using COUNT(DISTINCT) in SQL

The COUNT(DISTINCT column_name) function becomes even more powerful when used with GROUP BY, NULL values, and JOINs. These advanced scenarios help analyze unique data across different dimensions efficiently.

1. COUNT(DISTINCT) with GROUP BY

Using COUNT(DISTINCT) with GROUP BY helps count unique values within each category. This is useful when analyzing data across different segments, like finding unique customers per region.

Example: Counting Unique Customers Per Region

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    region VARCHAR(50)
);

INSERT INTO orders (order_id, customer_id, region) VALUES
(1, 101, 'North'),
(2, 102, 'South'),
(3, 103, 'North'),
(4, 101, 'North'),
(5, 104, 'East'),
(6, 102, 'South'),
(7, 105, 'West'),
(8, 101, 'North');

SELECT region, COUNT(DISTINCT customer_id) AS unique_customers 
FROM orders 
GROUP BY region;

Expected Output:

region

unique_customers

North

2

South

1

East

1

West

1

Explanation:

  • GROUP BY region groups the data by region.
  • COUNT(DISTINCT customer_id) ensures that duplicate customers in each region are counted only once.
  • Customer 101 appears three times in the North region but is counted once.

This helps businesses understand customer distribution across regions.

2. Handling NULL Values with COUNT(DISTINCT)

By default, COUNT(DISTINCT) ignores NULL values, meaning any missing data won’t be included in the count.

Example: Counting Unique Email Addresses

CREATE TABLE users (
    user_id INT PRIMARY KEY,
    email VARCHAR(100)
);

INSERT INTO users (user_id, email) VALUES
(1, 'alice@email.com'),
(2, 'bob@email.com'),
(3, NULL),
(4, 'alice@email.com');

SELECT COUNT(DISTINCT email) AS unique_emails FROM users;

Expected Output:

Unique_emails
2

Explanation:

  • The COUNT(DISTINCT email) removes duplicates (alice@email.com appears twice).
  • NULL values are ignored in the count.
  • Only two unique email addresses remain: alice@email.com and bob@email.com.

If you want to count NULLs as a unique value, use COALESCE() to replace NULLs with a placeholder:

SELECT COUNT(DISTINCT COALESCE(email, 'Unknown')) FROM users;

It ensures that NULL values are counted as a unique entry. This is useful for email marketing lists to ensure unique contacts are counted.

3. Using COUNT(DISTINCT) with JOINs

When working with multiple tables, SQL COUNT() with DISTINCT ensures unique values are counted across different datasets.

Example: Counting Unique Products Sold Per Customer

CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100),
    membership_status VARCHAR(20)
);

INSERT INTO customers (customer_id, name, membership_status) VALUES
(101, 'Alice', 'Premium'),
(102, 'Bob', 'Standard'),
(103, 'Charlie', 'Premium');

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    product_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

INSERT INTO orders (order_id, customer_id, product_id) VALUES
(1, 101, 201),
(2, 101, 202),
(3, 102, 201),
(4, 101, 201),
(5, 103, 203),
(6, 103, 204),
(7, 103, 203);

SELECT COUNT(DISTINCT o.product_id) AS unique_products_sold 
FROM orders o 
JOIN customers c ON o.customer_id = c.customer_id 
WHERE c.membership_status = 'Premium';

Expected Output:

unique_products_sold
3

Explanation:

  • The JOIN links orders to customers, filtering only those with 'Premium' membership.
  • COUNT(DISTINCT o.product_id) ensures we count only unique products purchased by premium customers.
  • Even though customer 103 bought product 203 twice, it is counted only once.

Using these techniques will make your SQL queries more powerful and help in efficient data analysis.

Potential Issue: If customers contains duplicate customer_id, it may overcount.

To avoid overcounting due to duplicate customer_id entries in the customers table, use a subquery with DISTINCT to select only unique customer_id values before joining with the orders table. This ensures each customer is counted once, even if there are multiple records for the same customer.

Also Read: SQL Vs MySQL: Difference Between SQL and MySQL

COUNT(DISTINCT) is useful, but it can slow down queries on large datasets. Let’s explore how you can optimize performance.

Performance Considerations for COUNT(DISTINCT)

While COUNT(DISTINCT column_name) is a powerful function for counting unique values, it can slow down queries on large datasets. Understanding how SQL processes this query and applying optimizations can significantly improve performance.

The COUNT(DISTINCT) function requires SQL to:

  • Scan the entire column to collect values.
  • Eliminate duplicates, which can be resource-intensive.
  • Count the remaining unique values.

On large tables, this can cause delays, especially if the column being counted is not indexed. The performance impact worsens if the table contains millions of records or if multiple COUNT(DISTINCT) queries run simultaneously.

Here are a few ways to optimize queries using Count Distinct in SQL:

  • Index the Column: Creating an index on the column being counted helps SQL retrieve unique values faster.
 CREATE INDEX idx_customer_id ON orders(customer_id);
  • Use WHERE to Reduce Data Size: Filtering unnecessary rows before counting improves efficiency.
 SELECT COUNT(DISTINCT customer_id) FROM orders WHERE order_date >= '2024-01-01';
  • Partition Large Tables: For huge datasets, partitioning (e.g., by date) reduces query load and improves performance.
PARTITION BY RANGE(order_date);

You can also choose alternative approaches:

  • Using GROUP BY Instead: If you need counts per category, GROUP BY is often more efficient than COUNT(DISTINCT).
 SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id;
  • Using DISTINCT Alone: If you only need unique values (not the count), using DISTINCT alone is faster.
 SELECT DISTINCT customer_id FROM orders;

Optimizing SQL COUNT() with DISTINCT ensures faster queries, especially when handling big data or high-traffic databases. 

Also Read: SQL vs PL SQL: Difference Between SQL & PL/SQL

Common Errors and Troubleshooting in COUNT(DISTINCT) Queries

While SQL COUNT() with DISTINCT is a powerful tool for counting unique values, it can lead to unexpected results or performance problems if not used carefully. These issues typically arise due to incorrect syntax, NULL handling, inefficient indexing, or unintended duplications from JOINs.

Below is a table highlighting common mistakes in COUNT(DISTINCT) queries, explanations of what goes wrong, and the solutions to fix them.

Error Type

Incorrect Query

Issue

Solution

Forgetting COUNT with DISTINCT SELECT DISTINCT column_name FROM table_name; Returns unique values but does not count them. Use COUNT(DISTINCT column_name): SELECT COUNT(DISTINCT column_name) FROM table_name;
Using COUNT(DISTINCT ) SELECT COUNT(DISTINCT *) FROM table_name; DISTINCT * is invalid; you cannot count distinct across multiple columns. Use a specific column: SELECT COUNT(DISTINCT column_name) FROM table_name;
Not Handling NULL Values SELECT COUNT(DISTINCT column_name) FROM table_name; NULL values are ignored, which might lead to unexpected results. Use COALESCE to count NULLs: SELECT COUNT(DISTINCT COALESCE(column_name, 'Unknown')) FROM table_name;
Slow Query on Large Datasets SELECT COUNT(DISTINCT customer_id) FROM orders; Large datasets cause performance issues due to scanning all rows. Optimize with indexing: CREATE INDEX idx_customer_id ON orders(customer_id);
Using COUNT(DISTINCT) in JOINs Inefficiently SELECT COUNT(DISTINCT a.column_name) FROM table1 a JOIN table2 b ON a.id = b.id; Duplicate rows from JOIN may lead to incorrect counts. Use GROUP BY or optimize the JOIN condition to avoid duplication.
Using COUNT(DISTINCT) with GROUP BY Incorrectly SELECT region, COUNT(DISTINCT column_name) FROM table_name; If GROUP BY is missing, SQL doesn't group results correctly. Ensure GROUP BY is included: SELECT region, COUNT(DISTINCT column_name) FROM table_name GROUP BY region;

By following these troubleshooting steps, you can improve query accuracy and performance when using COUNT(DISTINCT). 

Also Read: SQL Interview Questions and Answers for Beginners and Experienced Professionals

Mastering SQL requires both theory and practical experience. If you want to sharpen your skills, upGrad offers expert-led courses to help you excel.

How Can upGrad Help You Master COUNT(DISTINCT) in SQL?

upGrad, South Asia’s leading EdTech platform, offers specialized courses in SQL and database management that cover essential skills for efficient data handling. These courses provide a comprehensive curriculum, including foundational SQL concepts, advanced querying techniques, and performance optimization strategies.

With 10M+ learners trained, upGrad equips individuals with technical expertise, hands-on projects, and real-world applications, ensuring a strong grasp of database management and SQL analytics.

Here are some relevant courses to enhance your SQL learning journey:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today! 

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions

1. Can I use COUNT(DISTINCT) with multiple columns?

2. What’s the difference between COUNT(DISTINCT) and COUNT(*)?

3. Does COUNT(DISTINCT) always improve performance compared to COUNT(*)?

4. How do I count distinct values in multiple columns separately?

5. Why is my COUNT(DISTINCT) returning lower values than expected?

6. Can COUNT(DISTINCT) be used with HAVING instead of WHERE?

7. How can I check if COUNT(DISTINCT) is optimized in my query?

8. What happens if COUNT(DISTINCT) is used on a primary key column?

9. How does COUNT(DISTINCT) work in subqueries?

10. Is COUNT(DISTINCT) case-sensitive?

11. Can COUNT(DISTINCT) be used with window functions?

Mukesh Kumar

99 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

Suggested Blogs