DISTINCT
Beginner⏱️ 6 mins read
What You'll Learn
DISTINCT removes duplicate rows from a result set. When applied to multiple columns, it returns unique COMBINATIONS of those columns — not unique values per column independently. COUNT(DISTINCT col) counts unique non-null values in a column.
Syntax
SELECT DISTINCT col FROM table;
SELECT DISTINCT col1, col2 FROM table;
SELECT COUNT(DISTINCT col) FROM table;Example
-- Unique departments
SELECT DISTINCT department FROM employees;
-- Unique dept + job combinations
SELECT DISTINCT department, job_title
FROM employees;
-- Count unique customers who placed orders
SELECT COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;Common Mistakes
Assuming DISTINCT applies per column separately. SELECT DISTINCT a, b returns unique (a, b) pairs, not unique a values AND unique b values independently. DISTINCT also has performance overhead on large datasets — prefer GROUP BY for complex deduplication.
Interview Tips
Interviewers sometimes ask to deduplicate with row priority (e.g., keep the most recent row). For that, use ROW_NUMBER() window function rather than DISTINCT.
Practice
Find how many unique cities customers come from. Then find all unique combinations of city and country.