DSA Factory
Free SQL queries lessonsSQL queries · Stage 1 · Shaping the results · Step 1

Show each value once

Remove repeated rows from an answer with DISTINCT. About 6 minutes.

The same value, over and over

Ask the library which genres it stocks and the plain answer lists Novel forty times, once for every novel. You wanted the list of genres, not the list of books.

Add DISTINCT right after SELECT and any row that already appeared in the answer is skipped. The table itself is untouched. Only the answer is trimmed.

SELECT DISTINCT: each different row once.
In code
SELECT DISTINCT genre
FROM books;

Distinct applies to the whole row

With one column it is easy: each different value once. With two, DISTINCT looks at the pair. Two rows are repeats only when both columns match.

So SELECT DISTINCT genre, year can return Novel twice, if the years differ. Choose the columns first; DISTINCT then removes rows that look the same.

Two columns: a repeat means the same pair, not the same value.
SELECT DISTINCT genre FROM books
books
idtitlegenre
1Salt RoadNovel
2Paper BoatsPoetry
3Lamp StreetNovel
4Rain LettersStories
5Old FortPoetry

Novel: the first time it appears, so it goes into the answer.

Move 1 of 5
Quick check

What does SELECT DISTINCT city, branch FROM students return?

  1. AEach different city and branch pair, once
  2. BEach city once, then each branch once
  3. CEvery student, since every row has an id
Show the answer

Each different city and branch pair, once. DISTINCT compares the whole row of the selected columns.

Your problem

Cities we serve

The orders table has one row per order. Show every city that has at least one order, each city once, A to Z.

Tables
orders(id, customer, city, amount)

Up to 2,000 orders

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve