- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
- Home
- Blog
- Software Development
- COUNT(DISTINCT) in SQL: A Complete Guide to Counting Unique Values
COUNT(DISTINCT) in SQL: A Complete Guide to Counting Unique Values
Updated on Feb 27, 2025 | 15 min read
Share:
Table of Contents
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.
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.
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:
- Master of Design in User Experience
- Advanced SQL: Functions and Formulas
- Case Study using Tableau, Python and SQL
- Introduction to Database Design with MySQL
- AI-Powered Full Stack Development Course by IIITB
- Professional Certificate Program in UI/UX Design & Design Thinking
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.
Explore our Popular Software Engineering Courses
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
In-Demand Software Development Skills
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Read our Popular Articles related to Software
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?
Get Free Consultation
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
Top Resources