In a lot of cases multiple rows in a table may contain the same values for a given subset of fields. The DISTINCT keyword is used to select distinct combinations of column values and eliminate duplicate rows from the default results of a SELECT statement.
By default SELECT statements returns all rows including duplicates if you do not specify DISTINCT. For example, here is the result of searching for all Cities in the Employee table without distinct. The query result will return a list of cities, including duplicates.
SELECT City
FROM Employees
ORDER BY City
In the next example we will apply the DISTINCT keyword to the same query and find all the distinct cities in which Northwind has employees.
SELECT DISTINCT City
FROM Employees
ORDER BY City
Sample Database All the examples on this page use the:
AdventureWorks Lightweight (LT) Sample Database.
Pubs Sample Database or
Northwind Sample Database.
if you don't have an instance of these databases running on your pc, please follow the links to download and install them.
A database clothing apparel table might contain a Size field that identifies the size of a given apparel. It’s not unreasonable to assume that there may be multiple apparels with a Medium Size or even multiple apparels with the same combination of size and color.
The following example uses DISTINCT to generate a list of all unique titles in the DimEmployee table.
F
SELECT DISTINCT Title
FROM DimEmployee
ORDER BY Title;
.
--
GO
Note
Distinct treats multiple null values as duplicates. When distinct is included in a select statement, only one NULL is returned, no matter how many null values are encountered.
.
--
GO
.
--
GO
.
--
GO