Unique Values with DISTINCT

Which genres does the shop have? SELECT genre FROM games; gives 20 rows, one for each game, and most genres are there several times. DISTINCT, right after SELECT, keeps each different row only once:

SELECT DISTINCT genre
FROM games
ORDER BY genre;
genre
Action
Adventure
Puzzle
RPG
Racing
Simulation
Sports
Strategy

Eight genres instead of twenty rows. DISTINCT itself doesn't sort anything: the genres are in alphabetical order thanks to ORDER BY, and without it, they could come in any order. (RPG comes before Racing, because capital letters come before lowercase ones, as you saw at the beginning of this lesson.)

With several columns, DISTINCT removes only the rows that are the same in all of them. Which prices did each game sell for?

SELECT DISTINCT game_id, price
FROM order_items
ORDER BY game_id, price;
game_idprice
140
215
320
430
515
525
……

Most games are there once, but some twice, such as game 5, Shadow Ninja: it sold for $25, and for $15 on Black Friday. What counts is the combination of the values in the row, not each column on its own. NULL counts as a value too: if several rows have NULL, DISTINCT keeps one of them.

DISTINCT is written once, right after SELECT, and it applies to the whole row. Typical mistake: putting it in front of one of the columns. SELECT game_id, DISTINCT price FROM order_items; ends with the error near "DISTINCT": syntax error.

Instructions

The query in the editor shows the city of every customer, and the cities repeat. Change it, so that each city is there only once, in alphabetical order. The customers without a city add one more row, NULL:

city
NULL
Bristol
Leeds
London
Manchester

Below it, show the IDs of the customers who have ordered something: the column customer_id of orders, each ID only once, from the smallest. Customers 12 and 14 won't be there, because they've never ordered:

customer_id
1
2
3
4
…

Finally, find out which age ratings each genre has: show each combination of genre and age_rating only once, sorted by genre, and then by age rating:

genreage_rating
Action12
Action16
Action18
Adventure7
……

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/9