SQL DISTINCT Clause πΒΆ
Prerequisites: SELECT Statement
Mentor's Note: Sometimes your table has many repeated values (like city names or department IDs).
DISTINCTis the "De-duplicator". It ensures every value in your result is unique. π‘
π The Scenario: The City Map πΒΆ
Imagine you have a list of 1,000 customers. - The List: 500 customers are from "Surat", 300 from "Mumbai", and 200 from "Delhi". - The Question: "In which cities do we have customers?" - The Bad Answer: A list of 1,000 names (Surat, Surat, Surat...). - The DISTINCT Answer: "Surat, Mumbai, Delhi." β
π» 1. The Basic SyntaxΒΆ
Example: Finding Unique CitiesΒΆ
π» 2. DISTINCT on Multiple Columns πͺΒΆ
When you use DISTINCT with two columns, it looks for unique combinations.
-- Scenario: Find unique Department + Location pairs
SELECT DISTINCT dept_name, location
FROM departments;
How it works: - IT / Surat - IT / Mumbai (This is distinct because the location changed) - IT / Surat (This will be removed as it's a duplicate of the 1st row)
π» 3. Counting Unique Values π’ΒΆ
You can combine DISTINCT with the COUNT function.
-- Scenario: How many different cities do our students come from?
SELECT COUNT(DISTINCT city) FROM students;
π‘ Pro Tip: Performance WarningΒΆ
"Use
DISTINCTonly when you need to. To find unique values, the database has to sort and compare every row, which can be slow on tables with millions of records!"