Syllabus Lesson 68 of 239 · SQL & Databases
SQL & Databases

WHERE, ORDER BY & LIMIT

A query without a filter returns everything. WHERE keeps only the rows you want, ORDER BY sorts them, and LIMIT caps how many come back:

SELECT name FROM products
WHERE price <= 10           -- filter
ORDER BY price ASC          -- cheapest first (DESC for high-to-low)
LIMIT 5;                    -- at most 5

Pass user values as parameters with ?, never by gluing strings together (that is how SQL injection happens):

con.execute("SELECT name FROM products WHERE price <= ?", (max_price,))

Write affordable(con, max_price) returning the names of products whose price is <= max_price, cheapest first. Use a ? parameter. Press Run.

Your turn

Write affordable(con, max_price) that returns a list of product names where price <= max_price, ordered by price ascending (cheapest first). Pass max_price as a ? parameter, not by string formatting.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output