Skip to content

SQL DISTINCT Clause 💎

Mentor's Note: Sometimes your table has many repeated values (like city names or department IDs). DISTINCT is 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

SELECT DISTINCT column1, column2
FROM table_name;

Example: Finding Unique Cities

SELECT DISTINCT city FROM customers;

💻 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 DISTINCT only 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!"


📈 Learning Path