Skip to content

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
First rows of the products table
idnamecategoryunitsrevenue
1Kea mugkitchen1201440
2Tui bottleoutdoor952375
3Rimu boardkitchen601800
4Weka capoutdoor120960

4 more rows in the table. Your query sees all 8.