Lesson 3 of 12 · 6 min

Sorting and limiting

Without instructions, a database returns rows in no guaranteed order. ORDER BY sorts them:

SELECT name, price FROM products ORDER BY price;        -- cheapest first
SELECT name, price FROM products ORDER BY price DESC;   -- most expensive first

ASC (ascending, the default) goes from small to big, A to Z, early to late. DESC (descending) goes the other way.

You can sort by several columns. The second is only used when the first is equal:

SELECT name, city FROM customers ORDER BY city, name;

LIMIT

LIMIT keeps only the first few rows of the result. With ORDER BY, it answers "top N" questions:

SELECT name, joined FROM customers ORDER BY joined DESC LIMIT 2;  -- the 2 newest customers

ORDER BY comes after WHERE, and LIMIT comes last.

Your task

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

query.sql
-- The top 3 most expensive products

SQLite runs right here in your browser. The first run downloads about 0.7 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…