Hello! Welcome to your next lesson.
In our last session, we explored the GROUP BY clause, a powerful tool for splitting your data into subsets and performing calculations like COUNT() or AVG() on each group. You saw that GROUP BY country implicitly gives you a result for each unique country in your dataset.
Today, we'll focus on a more direct way to handle uniqueness: the DISTINCT keyword. While GROUP BY is for aggregation, DISTINCT is designed for one primary purpose: to remove duplicate rows from your query results. This is incredibly useful for data exploration, such as quickly finding out all the unique statuses a support ticket can have or listing all the different product categories you sell.
Your learning outcome for this lesson is to: Remove duplicate rows from results using the DISTINCT keyword.
We will cover its basic use, how it works with multiple columns, how it can be combined with aggregate functions, and even peek "under the hood" to understand its performance implications—a topic that should align with your interest in how systems work at a lower level.
The Basics: Getting a Unique List
The simplest use of DISTINCT is to get a list of unique values from a single column. Imagine you have a products table and want to see a list of all the unique supplier IDs to understand which suppliers are actively providing products. Without DISTINCT, you'd get a supplier ID for every single product, resulting in many duplicates.
The syntax is straightforward: you place the DISTINCT keyword immediately after SELECT and before the column names.
SELECT DISTINCT supplier_id
FROM products;
This query will return a list where each supplier_id appears only once, no matter how many products that supplier provides.
Let's watch a short video that demonstrates this fundamental use case.
Watch this clip from the 'Using DISTINCT in SQL' video by Database by Doug. It clearly introduces the keyword and shows its effect on a query.
Please watch from the beginning to 02:32. Pay attention to the 'before' and 'after' comparison to see exactly how DISTINCT removes the duplicate supplier_id values.
DISTINCT Across Multiple Columns
What happens when you use DISTINCT with more than one column? This is a crucial point: DISTINCT applies to the entire row of the result set. It doesn't find unique values for each column individually. Instead, it finds unique combinations of values across all selected columns.
For example, consider this query:
SELECT DISTINCT country, city
FROM customers;
This query will return rows where the combination of country and city is unique.
('USA', 'New York')is one distinct row.('USA', 'Boston')is another distinct row.- A second customer from
('USA', 'New York')would be considered a duplicate and would be removed from the result set.
The following video segment explains this concept clearly.
What Is SQL Distinct and How Can You Use It?
This clip from 'What Is SQL Distinct and How Can You Use It?' by Database Star explains how DISTINCT works when you select multiple columns.
Watch from 02:09 to 02:51. The key takeaway is that DISTINCT treats the entire selected row as the unit for determining uniqueness.
Test your understanding!
You have a logs table with columns: timestamp, service_name, error_level ('INFO', 'WARN', 'ERROR').
You want to find all the unique combinations of services and error levels that have occurred. For example, if the 'authentication-service' has produced both 'WARN' and 'ERROR' messages, you want to see both combinations in your results.
How would you write this query?
Show answer
SELECT DISTINCT service_name, error_level
FROM logs;
This query returns each unique pair of service_name and error_level found in the table, effectively giving you a summary of which services have produced which types of errors.
Under the Hood: How DISTINCT Works
Given your interest in low-level systems, you might wonder how the database actually finds and removes these duplicates. It's not magic—it's an algorithm with a computational cost. Database systems typically use one of two strategies:
-
Sorting: The database first sorts the entire result set based on the columns in your
SELECTlist. Once sorted, duplicate rows will be adjacent to each other, making them easy to identify and discard. The computational complexity of sorting is generally O(n log n), so this can be intensive for very large datasets. -
Hashing: The database creates a temporary hash table in memory. It then iterates through each row of the result set, computes a hash value for the row, and checks if that hash already exists in the table.
- If the hash is new, the row is added to the results and its hash is stored.
- If the hash already exists, the row is a duplicate and is discarded.
This approach is often faster (closer to O(n)) if there's enough memory to hold the hash table.
The database's query optimizer chooses which method to use based on factors like the size of the data, available memory, and whether the data is already sorted by an index. This is why DISTINCT isn't "free"—it adds a processing step to your query.
DISTINCT vs. GROUP BY
You might notice that SELECT DISTINCT column FROM table; produces the same list of unique values as SELECT column FROM table GROUP BY column;.
So when should you use which?
- Use
DISTINCTwhen you only want a list of unique values. It clearly states your intent and is often more performant because the database knows it doesn't need to prepare for any aggregate calculations. - Use
GROUP BYwhen you need to perform an aggregate function (likeCOUNT,SUM,AVG) on groups of data.
This next video segment directly compares the two.
Let's return to the Database by Doug video to see a comparison between DISTINCT and GROUP BY for finding unique values.
Watch from 03:35 to 04:58. The speaker explains that while the result is the same, GROUP BY is doing extra work by preparing for aggregations, making DISTINCT the more efficient choice for this specific task.
A Powerful Combination: COUNT(DISTINCT ...)
DISTINCT can also be used inside an aggregate function, which is an extremely common and useful pattern. This allows you to perform a calculation on only the unique values within a group.
The most frequent use is COUNT(DISTINCT column). Let's clarify the difference between the COUNT variations:
COUNT(*): Counts all rows in the group.COUNT(column): Counts all rows in the group wherecolumnis notNULL.COUNT(DISTINCT column): Counts the number of unique non-NULLvalues incolumnfor that group.
For example, SELECT agent_id, COUNT(DISTINCT customer_id) FROM service_tickets GROUP BY agent_id; would tell you how many unique customers each support agent has interacted with.
This final video clip demonstrates this powerful technique.
This last clip from the same video shows how to use DISTINCT inside the COUNT function.
Watch from 04:58 to 06:43. Notice the difference in the results when using COUNT(first_name) versus COUNT(DISTINCT first_name).
A Practical Warning: DISTINCT as a "Code Smell"
As you move into a developer or advanced technical support role, here is a high-ROI piece of advice. If you write a complex query with multiple JOINs and find you are getting unexpected duplicate rows, your first instinct might be to add SELECT DISTINCT to "fix" it.
Be careful. While this might clean up your output, it often just masks a deeper problem in your query logic. The duplicate rows are usually a symptom of a flawed JOIN condition (e.g., you joined on user_id but also needed to join on order_id).
Instead of using DISTINCT as a patch, treat the duplicates as a signal to investigate why they are appearing. Fixing the underlying JOIN is a much more robust and efficient solution than asking the database to fetch extra, incorrect data and then filter it out.
What Is SQL Distinct and How Can You Use It?
This segment from Database Star provides an excellent warning about this exact scenario.
Watch from 04:30 to 06:04. This is a critical piece of practical advice for writing professional, maintainable SQL.
Conclusion
Today you've added a versatile tool to your SQL toolkit. While simple on the surface, DISTINCT has important nuances in how it operates and where it's best applied.
Key Takeaways:
SELECT DISTINCTremoves entire duplicate rows from a result set.- When used on multiple columns, it finds unique combinations of values.
- It is not a "free" operation; the database uses sorting or hashing algorithms, which have a performance cost.
COUNT(DISTINCT column)is a powerful pattern for counting unique occurrences within a group.- Using
DISTINCTto hide duplicates from a badJOINis often a "code smell" that indicates a deeper problem with your query logic.
Preview of the Next Lesson:
We've now seen how to filter individual rows with WHERE and how to create groups with GROUP BY. But what if you want to filter the groups themselves? For example, "show me only the agents who have handled more than 50 tickets." The WHERE clause can't do this because it operates before grouping. In the next lesson, we will introduce the HAVING clause, which is designed specifically for this purpose.