runtime
09 / 88

lesson 09 Calculations & data quality · beginner

Unique values with DISTINCT

Return one copy of each distinct value.

the idea

DISTINCT removes duplicate output rows. It applies to the whole set of selected columns, not just the first column. NULL is kept once.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

customers4 columns · 8 rows
idinteger · keynametextcitytextjoined_attext
1AliceChicago2024-01-10
2BenAustin2024-02-12
3CaraSeattle2024-03-05
4DevChicago2024-04-20
5ElenaNULL2024-05-01

showing 5 of 8 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT DISTINCT city
FROM customers;

Watch for: Adding id makes every row unique, so it defeats this task.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. See duplicate cities first. Many customers share a city. The raw list repeats Chicago and Austin. DISTINCT will keep one row per distinct value.

    step-1.sql
    SELECT city
    FROM customers
    ORDER BY city;
  2. Keep each city once. DISTINCT removes duplicate output rows across the selected columns. NULL is kept once if it appears.

    step-2.sql
    SELECT DISTINCT city
    FROM customers;

challenge 1

Show each distinct customer city, including NULL.

Return cityany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.