Module 3 · Sorting and summarising

Avoid duplicates with DISTINCT

By the end you will be able to show each value or combination only once.

About 8 min

0 of 52 lessons

Before you start, you need

Sort and limit results

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.

Minimal syntax
SELECT DISTINCT column_name
FROM table_name;

See it in action

Which distinct cities appear in customers?

SQL
SELECT DISTINCT city
FROM customers
ORDER BY city;
Example result: 6 rows
city
Birmingham
Bristol
Edinburgh
Leeds
London
Manchester
  1. city is read from every customer and each value is kept only once.
  2. Several people from London produce a single London row. All those people still exist in customers.
  3. If you add name to SELECT DISTINCT, the pair of city and name is compared. That output answers a different question.
  4. 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

Not started

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.

Your turn

Solve this variation. Spot the part that has changed before you look for help.

Practice

Change what counts as a duplicate

Not started

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.

Key takeaways

  • DISTINCT removes repeats from the result.
  • It compares the whole selected combination.
  • The rows in the original table are kept.

Next: Summarise data with COUNT, SUM, AVG, MIN and MAX