login

SQL DISTINCT

SQL DISTINCT is used to eliminate the duplicated rows in the result of SELECT statement.
For example, to retrieve all the cities which employees live you can use SELECT statement as bellows:

SELECT city
FROM employees
city    
--------
Seattle
Tacoma
Kirkland
Redmond
London
London
London
Seattle
London

As you see you get the result with the duplicate row you may don’t expect therefore in this case you can use SQL DISTINCT to eliminate all of duplicated city in the result set by performing the following SQL statement:

SELECT DISTINCT city
FROM employees
city    
--------
Seattle
Tacoma
Kirkland
Redmond
London

You’ve put DISTINCT keyword before the column name you want it distinction in value. You can even put more columns after the DISTINCT keyword. At this time, the combination of all columns is used to evaluate the rows are duplicated or not.

For instance, you want to know all city and country information which employees live, you can perform the following query

SELECT DISTINCT city, country
FROM employees
city      country
-------- -------
Seattle USA
Tacoma USA
Kirkland USA
Redmond USA
London UK

At this time the combination of city and country is used to determine the record is unique (not duplicated) or not.

Beside DISTINCT keyword, you can use ALL keyword to indicate that you don’t want to eliminate duplicated records. Because ALL keyword is default to the SELECT statement so you don’t have to explicitly specify it in the SELECT statement.

How to use SQL Distinct correctly? come here to read SQL Distinct tutorial with examples, you will learn how to use SQL distinct in various examples.
Basically you can use SQL Distinct to eliminate duplicate rows.

Read On