Subqueries with IN and NOT IN
Filter by a list that another query builds.
A subquery can also return a list (one column, many rows). Then you use it with IN: WHERE id IN (SELECT book_id FROM loans) keeps books whose id appears in the loans table, which means books that have been borrowed. NOT IN keeps the ones that do not appear.
SELECT title FROM books
WHERE id NOT IN (SELECT book_id FROM loans);The inner query lists every borrowed book_id. The outer query keeps books not on that list: the ones never borrowed.
Many questions can be answered either with a JOIN or with IN. Use whichever you find easier to read.
Careful: if the inner list contains a NULL, NOT IN returns no rows at all. Add WHERE column IS NOT NULL inside the subquery when NULLs are possible.