SQL
4 min read
BEGINNER
DISTINCT
Quick AnswerSELECT DISTINCT removes duplicate result rows. It is useful for asking which customer identifiers appear in orders, rather than listing every order.
Core idea
SELECT DISTINCT removes duplicate result rows. It is useful for asking which customer identifiers appear in orders, rather than listing every order.
Minimal example
sql
SELECT DISTINCT customer_id FROM orders ORDER BY customer_id;Expected rows (in order):
text
12How it works
DISTINCT applies to the entire selected tuple, not just the first column. Two rows with the same customer_id but different id remain distinct when both columns are selected. Duplicate elimination does not delete stored rows and does not guarantee ordering. NULL details are covered later.
Practical example
sql
SELECT DISTINCT customer_id, id FROM orders ORDER BY customer_id, id;Expected rows (in order):
text
1 | 1011 | 1022 | 103Common mistake and practice
Do not add DISTINCT merely to hide a query mistake. Compare the first example with SELECT customer_id FROM orders ORDER BY id; explain why it returns three rows.