SQL DISTINCT Clause

When fetching data from a database table, the result set may contain duplicate rows or values. If you want to remove these duplicate values you can specify the keyword DISTINCT directly after the SELECT keyword, as demonstrated below:

Syntax

The DISTINCT clause is used to remove duplicate rows from the result set:

SELECT DISTINCT column_list FROM table_name;

Here, column_list is a comma separated list of column or field names of a database table (e.g. name, age, country, etc.) whose values you want to fetch.

Example

SELECT city FROM customers;

If you see the output carefully, you'll find the city "Madrid" appears two times in our result set, which is not good. Well, let's fix this problem.

Removing Duplicate Data

The following statement uses DISTINCT to generate a list of all city in the customers table.

Example

SELECT DISTINCT city FROM customers;