SQL ยท Chapter 4 of 42

SELECT DISTINCT

`SELECT DISTINCT` returns only unique combinations of the listed columns.

Use it to see 'what values exist' in a column.

Syntax
SELECT DISTINCT column FROM table;

Multiple columns

`DISTINCT col1, col2` treats the pair as one value โ€” a row is duplicate only if BOTH match.

Performance

DISTINCT sorts/hashes rows to deduplicate, so it can be slow on huge tables. A GROUP BY often achieves the same.

Example 1 (sql)
SELECT DISTINCT country FROM users;
Output
country
India
USA
UK

List each country once, even if many users share it.

Example 2 (sql)
SELECT DISTINCT country, city FROM users;
Output
country | city
India   | Delhi
India   | Mumbai
USA     | NY

Distinct city+country pairs.

Key points

  • Removes duplicate rows.
  • Works on the combination of listed columns.
  • Can be slower on very large tables.
  • COUNT(DISTINCT col) counts unique values.
๐Ÿ’ก Note: `COUNT(DISTINCT col)` counts unique non-NULL values โ€” a common analytics pattern.

๐Ÿ“ Quick Quiz

1. SELECT DISTINCT removes:

2. `SELECT DISTINCT a, b`: a row is duplicate when:

3. To count unique cities use: