๐ŸŽ“ A1Learner
๐Ÿ”

SQL Distinct

DISTINCT is a keyword that removes duplicate rows from a result. A value that appears many times in the table appears once in the answer.

Countries with repeats

A plain query returns one row per customer. The USA appears twice, because two customers live there.

SELECT country FROM customers;

Countries without repeats

DISTINCT drops the repeated USA row. Seven rows come back for the eight customers.

SELECT DISTINCT country FROM customers;

Distinct cities

Austin appears twice in the customers table, so DISTINCT returns it once. The missing city stays in the answer as NULL.

SELECT DISTINCT city FROM customers;

Example

SELECT DISTINCT category FROM products;

Key points

  • DISTINCT: the keyword that drops repeated rows from a result
  • DISTINCT sits right after SELECT in the query.
  • Two rows count as duplicates when every value matches.
  • A plain SELECT keeps every row, duplicates included.
  • Use DISTINCT to list the different values a column holds.

In this example, the products table holds eight rows across five categories. DISTINCT keeps one row for each category and drops the repeats. The answer lists each category once.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DB Fiddle

Exercise

What does DISTINCT do to a result?