Skip to content
CodeItRaw
SQL: Subqueries

Lesson 2/2

The subqueries so far ran once and were done. A correlated subquery looks at the current row of the outer query and is evaluated again for every row: "does this author have at least one book?"

SELECT a.name
FROM authors AS a
WHERE EXISTS (
SELECT 1 FROM books AS b WHERE b.author_id = a.id
);
EXISTS looks at whether the inner query returns at least one row; what it returns does not matter, hence SELECT 1. The a.id inside comes from the outer row: that is what makes the connection. For the opposite, NOT EXISTS.

The same idea finds "the most expensive book of each genre": pick a book if its price equals the highest price in its own genre. The subquery works out, for each book, the highest price of that book's genre: WHERE b.price = (SELECT MAX(price) FROM books WHERE genre = b.genre).

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

    Sellers

    SQL query

  2. 02

    Top of each department

    SQL query

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