✅ DISTINCT is used to:
Remove duplicate rows from the result set.
- It ensures that the output has only unique rows — no duplicates.
- It compares all selected columns — if all columns in a row match, it’s considered a duplicate.
When Do You Use DISTINCT?
- When you want to get only unique values.
- When you want to avoid duplicates in your results.
- When you’re doing reporting or analytics and you need clean, non-repeating data.
Example
Imagine a Products table:
| product_id | category |
|---|---|
| 1 | Electronics |
| 2 | Books |
| 3 | Electronics |
| 4 | Books |
| 5 | Furniture |
Without DISTINCT
SELECT category FROM Products;
Result:
| category |
|---|
| Electronics |
| Books |
| Electronics |
| Books |
| Furniture |
(You get duplicates.)
With DISTINCT
SELECT DISTINCT category FROM Products;
Result:
| category |
|---|
| Electronics |
| Books |
| Furniture |
✅ Only unique categories are shown — duplicates are removed.
How DISTINCT Works
- SQL compares all selected columns together.
- If two rows are exactly the same in all selected columns, only one is kept.
Example with two columns
SELECT DISTINCT product_id, category FROM Products;
Now, it looks at the combination of product_id and category — if they’re unique together, the row stays.
Key Points
| Point | Meaning |
|---|---|
| Removes duplicates | Returns only unique rows. |
| Works on all selected columns | Duplicates are based on all selected columns. |
Often used with COUNT(DISTINCT column) | To count unique values. |
Important Tip
DISTINCTis expensive for large datasets because SQL must sort or hash to find duplicates.- If you don’t need uniqueness, avoid it for better performance.
In Short
DISTINCTis used to remove duplicate rows and make your result set contain only unique rows.