ORDER BY & LIMIT
Put the rows in an order that means something, then take the top few
0 of 3 done · Lesson 2 of 8
Understand
Rows come back in whatever order the database found them, which is no order at all. Every time someone asks for the best sellers, the slowest tickets or the ten biggest invoices, they are asking two questions at once: sort it by something, then cut the list short. ORDER BY does the sorting and LIMIT does the cutting, in that order.
SELECT which_columns_you_want FROM where_it_lives ORDER BY what_to_sort_by LIMIT how_many_rows;
SELECTwhich columns you wantFROMwhich tableWHEREwhich rows to keepORDER BYwhat to sort byLIMIThow many rows to keep
The tables you are working with
8 rows
| id | name | category | units | revenue |
|---|---|---|---|---|
| 1 | Kea mug | kitchen | 120 | 1440 |
| 2 | Tui bottle | outdoor | 95 | 2375 |
| 3 | Rimu board | kitchen | 60 | 1800 |
| 4 | Weka cap | outdoor | 120 | 960 |
4 more rows in the table. Your query sees all 8.