Home › Learn › SQL › Reading rows

ORDER BY and LIMIT

Lesson 5 of 26. Sort the result and take the first few rows.

Rows come back in no guaranteed order unless you ask: ORDER BY price sorts ascending, ORDER BY price DESC descending, and ORDER BY category, price DESC sorts by category and then by price within each category. LIMIT 3 keeps only the first three rows of the sorted result, which is how you get "the top three" of anything.

The clauses have a fixed order: SELECT, FROM, WHERE, ORDER BY, LIMIT. This lesson checks the order of the rows, not just their contents, and the column names too: this course ends in a report that is built from views, one per module, and this query is the first of them, so the project needs its columns named exactly.

SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 2;

Your task

Show the id, name, and price of the three most expensive products, most expensive first.

Part of the final project. top_products is the view of the three most expensive products, which the report flags as featured. It is saved in this browser and loaded into Project: the order report when you get there.

Hint 1

ORDER BY price DESC, then LIMIT 3.

Show the solution
SELECT id, name, price FROM products ORDER BY price DESC LIMIT 3;

    Runs SQLite compiled to WebAssembly in this tab; the database is rebuilt before every run.