DISTINCT in MySQL — How It Works

What the MySQL DISTINCT function does, with an example.

Published October 22, 2026

DISTINCT removes duplicate rows from a result. It applies to the whole combination of selected columns.

How it works

COUNT(DISTINCT col) counts unique values.

Try it in MySQL

SELECT DISTINCT city FROM users
unique cities
SELECT COUNT(DISTINCT city) FROM users
42
SELECT DISTINCT city, country FROM users
unique pairs

Practical examples

Example 1

SELECT DISTINCT city FROM users;
-- unique cities

Example 2

SELECT COUNT(DISTINCT city) FROM users;
-- 42

Example 3

SELECT DISTINCT city, country FROM users;
-- unique pairs

Use it in a real query

SELECT DISTINCT city FROM users;

Common mistakes

  • Expecting DISTINCT to apply to one column only.
  • Using it to mask a bad join.
  • Performance on large unindexed columns.

Key takeaways

  • DISTINCT in one line: DISTINCT removes duplicate rows from a result.
  • Try queries in a test database first.
  • Check NULL handling and data types.

FAQ

DISTINCT vs GROUP BY?

Often equivalent; GROUP BY lets you aggregate.

Does DISTINCT work in other databases?

Most have an equivalent, but names and syntax vary between MySQL, PostgreSQL, SQL Server and SQLite.

More SQL articles