runtime
08 / 88

lesson 08 Filtering & sorting · beginner

Sort & limit

Order your results and choose how many rows to return.

the idea

ORDER BY sorts the output; ASC is ascending and DESC descending. LIMIT keeps a number of rows after sorting. Use a secondary key when ties need deterministic ordering.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT name, price
FROM products
ORDER BY price DESC, name ASC
LIMIT 3;

Watch for: LIMIT without ORDER BY does not promise which rows you get.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Sort prices before cutting. ORDER BY decides which rows come first. LIMIT only makes sense after the sort, or you get an arbitrary cut.

    step-1.sql
    SELECT name, price
    FROM products
    ORDER BY price DESC, name ASC;
  2. Keep the top of the sorted list. DESC puts expensive products first. LIMIT 3 keeps only the first three after sorting.

    step-2.sql
    SELECT name, price
    FROM products
    ORDER BY price DESC, name ASC
    LIMIT 3;

challenge 1

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

Return namepricerows in the order asked

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.