What do we do when a subquery returns many rows? Then we cannot compare them with a single
=. The IN operator comes to the rescue - it checks whether a value is on the list returned by the subquery.1SELECT tytul
2FROM ksiazki
3WHERE autor_id IN (SELECT id FROM autorzy WHERE kraj = 'Polska');First the subquery returns the list of
ids of all authors from Poland. Then the outer query picks those books whose autor_id is on that list. This way a single query joins two shelves: ksiazki and autorzy.Without a subquery we would have to first write down the
ids of the Polish authors and then paste them manually into the query:1SELECT tytul FROM ksiazki WHERE autor_id IN (1, 4, 7);The subquery does that for us - and updates the list itself whenever new authors arrive in the Library.
The
NOT IN operator works the other way around - it picks rows whose value is not on the list:1SELECT tytul
2FROM ksiazki
3WHERE kategoria_id NOT IN (SELECT id FROM kategorie WHERE nazwa = 'Poezja');This is how we find all books outside the poetry section.
@name