Before you start, you need
Show combinations without repeats
Several customers may live in London. If you need a list of cities, seeing London five times does not help. DISTINCT keeps a single occurrence of each value in the result.
Write it straight after SELECT: SELECT DISTINCT city. All the customers are still stored; only the list you see changes.
If you choose several columns, SQL compares the whole combination. SELECT DISTINCT category, stock removes repeated pairs, not individual categories. A category with different stock levels can appear on several rows.
First decide which list you need: cities, categories or pairs of values. Adding a column changes what counts as a repeat.
SELECT DISTINCT column_name
FROM table_name;See it in action
Which distinct cities appear in customers?
SELECT DISTINCT city
FROM customers
ORDER BY city;| city |
|---|
| Birmingham |
| Bristol |
| Edinburgh |
| Leeds |
| London |
| Manchester |
- city is read from every customer and each value is kept only once.
- Several people from London produce a single London row. All those people still exist in customers.
- If you add name to SELECT DISTINCT, the pair of city and name is compared. That output answers a different question.
- DISTINCT goes straight after SELECT, before the column list.
Practice with help
Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.
Guided practice
Get each category once
Write a query that returns the distinct product categories, sorted alphabetically.
Expected result: 5 rows with the column category, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
The output must show each category only once.
Select category.
Sort the result to make it easier to read.
Solution explained
SELECT DISTINCT category FROM products ORDER BY category;The result has one row for each distinct category.
Your turn
Solve this variation. Spot the part that has changed before you look for help.
Practice
Change what counts as a duplicate
Show the distinct pairs of category and stock. Sort by category and stock, both ascending.
Expected result: 9 rows with the columns category, stock, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Each result row represents a pair, not just a category.
DISTINCT applies to both columns in the SELECT.
Select category and stock, and sort by both.
Solution explained
SELECT DISTINCT category, stock FROM products ORDER BY category, stock;Whole pairs are deduplicated. A category repeated with different stock levels is a valid result.
Key takeaways
- DISTINCT removes repeats from the result.
- It compares the whole selected combination.
- The rows in the original table are kept.