DISTINCT
SELECT DISTINCT column FROM table returns each value once, with duplicates removed. With several columns, DISTINCT applies to the whole combination: SELECT DISTINCT country, city returns each country-city pair once. For a count of unique values use COUNT(DISTINCT column).
Syntax
SELECT DISTINCT column1, column2 FROM table;Examples
SELECT DISTINCT country FROM customers ORDER BY country;Result: Each country once, alphabetically
SELECT DISTINCT country, city FROM customers;Result: One row per unique country and city combination
A country appears more than once if it has several cities.
SELECT COUNT(DISTINCT customer_id) AS buyers FROM orders;Result: buyers 42
Counts customers who placed at least one order, each counted once.
Common mistakes
- Writing SELECT name, DISTINCT country is a syntax error; DISTINCT comes right after SELECT and applies to all listed columns.
- Expecting DISTINCT to make one column unique while other columns vary; it dedupes whole rows, so use GROUP BY with aggregates to pick one row per value.
- Using DISTINCT to hide duplicate rows produced by a bad join; fix the join condition instead, because DISTINCT is slower and hides the real problem.
Practice DISTINCT
These drills check your answer on live data, free, no account needed.
- Each country onceList every country that has at least one customer, each country only once.
- Customers who orderedHow many different customers have placed at least one order? Return a single number.
Questions
What is the difference between DISTINCT and GROUP BY?
SELECT DISTINCT country and SELECT country ... GROUP BY country return the same unique list. GROUP BY additionally lets you add aggregates such as COUNT(*) per group, so it is the one to use when you need numbers per value.
How do I count unique values in SQL?
COUNT(DISTINCT column). For unique combinations of two columns, use a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT a, b FROM t) AS x.
Does DISTINCT work on one column only?
No, it applies to every column in the SELECT list. PostgreSQL has DISTINCT ON (column) to keep the first row per value; in SQLite use ROW_NUMBER() OVER (PARTITION BY column) and keep row number 1.
Related
- COUNT(DISTINCT)COUNT(DISTINCT column) counts how many different values a column holds, ignoring NULL. Unique customers, distinct values per group, distinct pairs of columns.
- GROUP BYGROUP BY collapses rows that share a value into one row per group so you can count, sum or average them. One or several columns, the must-appear rule, HAVING.
- ROW_NUMBERROW_NUMBER() OVER (ORDER BY ...) assigns 1, 2, 3 to rows; with PARTITION BY it restarts per group. Latest row per customer, remove duplicates, paginate.
- SELECTHow to write a SQL SELECT: choose columns from a table, select everything with *, compute expressions, and combine it with WHERE, ORDER BY and LIMIT.