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;| title | price |
|---|---|
| Cube Logic | 5 |
| Word Quest | 10 |
| Bakery Story | 15 |
| Ocean Deep | 15 |
| Pixel Racer | 15 |
| … | … |
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:
| name | city |
|---|---|
| Ava Green | NULL |
| Henry Scott | NULL |
| Max Baker | Bristol |
| Mia Lewis | Bristol |
| … | … |
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:
| genre | title | price |
|---|---|---|
| Action | Robot Rebellion | 40 |
| Action | Star Pilots | 35 |
| Action | Zombie Town | 30 |
| … | … | … |
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_id | id |
|---|---|
| 1 | 26 |
| 1 | 14 |
| 1 | 4 |
| 1 | 1 |
| … | … |
Start programming for free
4/12