SQL DISTINCT

SELECT DISTINCT removes duplicate rows from a result. It looks at all selected columns together: two rows are duplicates only if every column matches.

COUNT(DISTINCT column) counts unique values, which is a very common question in analysis.

Syntax

SELECT DISTINCT column1, column2
FROM table_name;

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

distinct.sql · PostgreSQL
Loading editor…

Examples

1. Unique categories

SELECT DISTINCT category FROM products;

Each category once.

2. Unique combinations

SELECT DISTINCT country, city FROM customers;

Each country and city pair once.

3. Count unique values

SELECT COUNT(DISTINCT country) FROM customers;

How many countries we sell to.

Common mistakes

  • Using DISTINCT to hide duplicates caused by a wrong JOIN. Fix the join instead.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 10 pts

List each product category exactly once.

challenge.sql · PostgreSQL
Loading editor…

FAQ

Is DISTINCT the same as GROUP BY?

For simply removing duplicates they give the same result. Use GROUP BY when you also need aggregates per group.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →