Sorting by Several Columns

Some games cost the same: Pixel Racer, Ocean Deep and Bakery Story all cost $15. When you sort by price, they're a tie, and the order in which they come is up to the database. Just like the order of rows without ORDER BY, it isn't guaranteed.

To break ties, add a second column, after a comma. The rows are sorted by the first column, and the rows with the same value in it by the second one:

SELECT title, price
FROM games
ORDER BY price, title;
titleprice
Cube Logic5
Word Quest10
Bakery Story15
Ocean Deep15
Pixel Racer15
……

Now the three games for $15 come in alphabetical order. If two columns aren't enough, add a third one, and so on. A column whose values never repeat, such as id, breaks every tie for sure.

Each column has its own direction. DESC applies only to the column it follows: ORDER BY price DESC, title sorts the prices from the highest, but games with the same price still from A to Z. To sort both columns in descending order, write DESC after each of them: ORDER BY price DESC, title DESC.

Typical mistake: expecting one DESC at the end to apply to all the columns. In ORDER BY age_rating, title DESC, the age ratings still go from the lowest; only the titles of games with the same rating go from Z to A.

You can also sort by a column that the query doesn't show. This query lists just the names of the customers, from the one who joined last. It's the same order as in your second query in the previous exercise, only without the dates:

SELECT name
FROM customers
ORDER BY joined DESC;
name
Max Baker
Sophie Adams
Henry Scott
…

Instructions

Show the name and the city of every customer, sorted by city, and the customers from the same city by name. The customers without a city come first:

namecity
Ava GreenNULL
Henry ScottNULL
Max BakerBristol
Mia LewisBristol
……

Below it, show the genre, the title and the price of every game, sorted by genre from A to Z, and the games of each genre from the most expensive:

genretitleprice
ActionRobot Rebellion40
ActionStar Pilots35
ActionZombie Town30
………

Finally, show the ID of the customer and the ID of every order (the columns customer_id and id of orders, in this order). Sort the orders by the customer's ID, and the orders of each customer from the newest one. The column ordered_at decides, but don't show it:

customer_idid
126
114
14
11
……

Start programming for free

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

Or sign up with:

3/9