Skip to content
CodeItRaw
SQL: Subqueries

Lesson 1/2

Some questions are asked in two steps: "what is the average price?" and "which ones cost more than that?". Instead of copying the first answer by hand, you write that query in brackets inside the second. The inner query runs first and its answer is put in its place.

SELECT title, price
FROM books
WHERE price > (SELECT AVG(price) FROM books);
The inner query returns a single value (one row, one column), which is why it can be compared with >. You cannot write the aggregate straight into WHERE price > AVG(price); a subquery is the way to do it.

When the inner query returns a list, you use IN: WHERE author_id IN (SELECT id FROM authors WHERE country = 'TR'). First the numbers of the authors in Turkey are found, then the books carrying one of those numbers are picked.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Above average

    SQL query

  2. 02

    The sales city

    SQL query

If you would rather not wait for the order, every problem is open without locks: Problem list