ORDER BY
SQL · Unit 3: Sorting and limiting
- Full plan
- SQL
- 10 exercises
Up to now the catalog has always looked the same, with the Keyboard on top and the Speaker at the bottom. That's how someone entered them, and it's no use to any customer.
What's the cheapest thing in the store, and what comes next? ORDER BY goes at the end of the query, after the WHERE if there is one, and says which column the rows are sorted by. They go from lowest to highest.
SELECT name, price
FROM products
ORDER BY price;Returns
| name | price |
|---|---|
| Cable | 5.25 |
| Mouse | 19.9 |
| Keyboard | 45.5 |
| Headphones | 59.9 |
| Speaker | 74 |
| Monitor | 189 |
| Tablet | 320 |
| Laptop | 899 |
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
Someone wants to spend between 40 and 200, and see the cheapest first. What does this query return?
2. Multiple choice
The weekly orders report has no
ORDER BY, and for months it has listed them from the oldest order to the newest. What guarantees it looks the same on Monday?3. Complete the code
Someone is looking for a gift under 100 and wants to see the most expensive first, so the gift doesn't look cheap. Fill in the blanks.
4. Predict the output
The store is inviting its customers under 30 to a workshop. Whoever is at the door wants the list in alphabetical order, to find each name fast. What does this query return?
5. Find the bug
The history for Luke, customer 2, should start with his most recent order. The query runs without an error, but the history comes out backward. Which line has the problem?
6. Put the lines in order
The store is giving its Denver customers a free course and forming the groups by age. Put in order the query that shows each one's name and age, from youngest to oldest. One line doesn't belong.
7. Complete the code
The printed catalog ends with an index of what's in stock, to look up each product by name, from A to Z. Fill in the blank.
8. Predict the output
Here the sort is on a column the
SELECTdoesn't show. In Accessories, the Keyboard costs 45.5, the Mouse 19.9, and the Cable 5.25. What does this query return?9. Put the lines in order
The keyboards and the mice, products 1 and 2, went out with a defect. Someone has to call the people who ordered them, starting with the most recent order. Put the query in order. One line doesn't belong.
10. Write the code
The store is launching a discount for its customers over 30 that grows with age, and wants whoever gets the most at the top of the list. Write a query that shows the
nameand theageof those customers, in that order, starting with the oldest.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.