×

sql · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A in brackets hands its answer to the main query.

Which snacks cost more than average? You could ask for the average, write it down, then type it into a second query. But when prices change, your number goes stale.

Instead, put the first query in brackets right where the number would go. That is a subquery. SQLite works out the bracketed part first, then uses its answer as the value.

A subquery used like this must give back exactly one value: one column and one row. An aggregate such as AVG or MAX is perfect.

SELECT name, price FROM snacks
WHERE price > (SELECT AVG(price) FROM snacks)
ORDER BY price DESC;

If a subquery gives back several rows, SQLite quietly uses the first, so make sure it gives one.