CodeBlanks Logo Icon CodeBlanks

DISTINCT with aggregates

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

query.sql
-- sorted distinct
SELECT
FROM customers

Sample solution

query.sql
SELECT DISTINCT city
FROM customers
ORDER BY city

Expected 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

Question
SELECT DISTINCT city FROM customers
____ city;
Answer
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

All lessons in Beginner