MySQL: DISTINCT Clause

This MySQL tutorial explains how to use the MySQL DISTINCT clause with syntax and examples.

Description

The MySQL DISTINCT clause is used to remove duplicates from the result set. The DISTINCT clause can only be used with SELECT statements.

Syntax

The syntax for the DISTINCT clause in MySQL is:

SELECT DISTINCT expressions

FROM tables

[WHERE conditions];

Parameters or Arguments

expressions

The columns or calculations that you wish to retrieve.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. The conditions that must be met for the records to be selected.

Note

Example - With Single Expression

Let's look at the simplest MySQL DISTINCT clause example. We can use the MySQL DISTINCT clause to return a single field that removes the duplicates from the result set.

For example:

SELECT DISTINCT state

FROM customers;

This MySQL DISTINCT example would return all unique state values from the customers table.

Example - With Multiple Expressions

Let's look at how you might use the MySQL DISTINCT clause to remove duplicates from more than one field in your SELECT statement.

For example:

SELECT DISTINCT city, state

FROM customers;

This MySQL DISTINCT clause example would return each unique city and state combination from the customers table. In this case, the DISTINCT applies to each field listed after the DISTINCT keyword, and therefore returns distinct combinations.