DISTINCT with aggregates
- SQL course
- Beginner
- Lesson 68/115
- 4 min
Count unique values with COUNT(DISTINCT ...).
DISTINCT and ORDER BY
DISTINCT and ORDER BY can be combined. Deduplication happens first, then sorting.
SELECT DISTINCT city FROM customers
ORDER BY city;This query sorts unique cities alphabetically.
city is selected from customers (DISTINCT removes duplicates). The result is sorted by city in ascending order.
DISTINCT and ORDER BY — details
ORDER BY must use one of the DISTINCT columns; otherwise it is ambiguous. DESC gives descending order.
Practice DISTINCT and ORDER BY
Select unique cities alphabetically from customers.
Starter code
-- sorted distinct
SELECT
FROM customersSample solution
SELECT DISTINCT city
FROM customers
ORDER BY cityExpected output
city Bursa İstanbul İzmir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which order do DISTINCT and ORDER BY run in?
- ORDER BY first, then DISTINCT
- At the same time
- DISTINCT first, then ORDER BY Correct answer
- Random
Explanation: Deduplication first, then sorting.
2 Sorted distinct
SELECT DISTINCT city FROM customers
____ city;
SELECT DISTINCT city FROM customers
ORDER BY city;
Explanation: ORDER BY is the right answer.
3 DISTINCT with aggregates: match the terms
| Term | Meaning |
|---|---|
DISTINCT |
deduplicate |
ORDER BY |
sort |
ASC |
ascending |
DESC |
descending |