Sorting by several columns
SQL · Unit 3: Sorting and limiting
- Full plan
- SQL
- 10 exercises
The store is sending a survey to its customers under 35, from youngest to oldest. Luke and Dylan are both 27. Which one goes first?
With a plain ORDER BY age, SQL makes no promise. A second column, after a comma, decides between the ones that tie on the first.
SELECT name, age
FROM customers
WHERE age < 35
ORDER BY age, name;Returns
| name | age |
|---|---|
| Mason | 19 |
| Dylan | 27 |
| Luke | 27 |
| Ann | 34 |
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
The list of everything that costs less than 70 goes by section and, within each section, by name. What does this query return?
2. Multiple choice
The order history uses
ORDER BY placed, and some days have two orders. The owner doesn't care which of the two goes first, but wants the list to look the same every time. What do you add afterplaced?3. Complete the code
The warehouse is packing the shipments for Denver and Austin and wants the list by city and, within each city, by name. Fill in the blank.
4. Predict the output
The owner is going to restock anything with fewer than 6 in stock. Lowest stock goes first and, on a tie, the most expensive. What does this query return?
5. Complete the code
The warehouse ships the orders of more than one unit. The biggest goes out first and, among orders of the same size, the one that has been waiting longest. Fill in the blanks.
6. Find the bug
The history from January 12 on should start with the most recent day and, within each day, with the biggest order. The query runs without an error, but the earliest day is on top. Which line has the problem?
7. Put the lines in order
What's the biggest order each product has had? Put in order the query that shows the orders for products 1, 2, and 3, kept together by product and, in each one, with the biggest order on top. One line doesn't belong.
8. Predict the output
In Accessories, the Keyboard costs 45.5 and there are 12. The Mouse costs 19.9 and there are 30. There are no Cables left. What does this query return?
9. Put the lines in order
A shelf holds 30 units. For each product with fewer than 10, the stock clerk wants to see how many more it takes to fill its shelf, starting with the one that needs the most. The Cable and the Speaker tie, and the name decides between them. Put the query in order. One line doesn't belong.
10. Write the code
The owner wants to know what the inventory is worth. For each product, show three columns, in this order: its
category, itsname, and the value of its stock, which isprice * stock. The rows go by category in alphabetical order and, within each category, with the most valuable product first.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.