SELECT DISTINCT
The SELECT DISTINCT statement returns only different (unique) values.
💡 DISTINCT removes duplicate rows from your results, giving you only unique values.
Basic Syntax
SELECT DISTINCT column1, column2
FROM table_name;
Simple Example
Without DISTINCT:
SELECT city FROM customers;
| city |
|---|
| New York |
| Los Angeles |
| Chicago |
| New York |
With DISTINCT:
SELECT DISTINCT city FROM customers;
| city |
|---|
| New York |
| Los Angeles |
| Chicago |
DISTINCT on Multiple Columns
SELECT DISTINCT city, state FROM customers;
Returns unique combinations of city AND state.
DISTINCT with COUNT
-- How many different cities?
SELECT COUNT(DISTINCT city) FROM customers;
| COUNT(DISTINCT city) |
|---|
| 8 |
DISTINCT vs GROUP BY
-- These produce the same result:
SELECT DISTINCT city FROM customers;
SELECT city FROM customers GROUP BY city;
-- But GROUP BY is more powerful:
SELECT city, COUNT(*) FROM customers GROUP BY city;
✏️ Exercise: Find all unique product categories from a 'products' table
See Solution
SELECT DISTINCT category FROM products;
✅ Key Takeaways
- DISTINCT removes duplicate rows from results
- Works on single columns or combinations of columns
- Can be used with COUNT to count unique values
- Treats NULL as a unique value
- GROUP BY is similar but more powerful for aggregation