Reading data with SELECT
DISTINCT and duplicate results
Explain repeated values in a projection and remove them when needed.
Lesson 8 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. A customer list has 20 rows, but several customers share a city. If you need a list of cities rather than a list of customers, repeated city values get in the way.
Run the example
SELECT DISTINCT City
FROM dbo.Customers
ORDER BY City;Read it step by step
- SELECT City FROM dbo.Customers would return 20 rows, with London and other cities repeated.
- DISTINCT compares the selected values and keeps one row for each different City. It does not delete or update customer records.
- ORDER BY City sorts the eight remaining names alphabetically so the result is easy to inspect.
Check the result
| City |
|---|
| Birmingham |
| Bristol |
| Cardiff |
| Leeds |
| Leicester |
| London |
| Manchester |
| York |
There are eight rows because the unmodified v1.0.0 dataset has eight city names. DISTINCT works on the whole selected combination: SELECT DISTINCT City, Region asks for unique city-and-region pairs. Selecting CustomerID too would yield 20 rows because every customer ID is unique.
Practice
Find the distinct Region values in Customers. How many are there?
Check your answer and expected result
Reveal answer
SELECT DISTINCT Region FROM dbo.Customers ORDER BY Region;| Region |
|---|
| Midlands |
| North |
| South |
| West |
The four values are Midlands, North, South, and West.
Your progress
Reveal the check answer or reach the end to complete this lesson.