IntermediateLesson 7 of 15
Subqueries, EXISTS & Set Operations – SQL
Nesting queries, correlated subqueries, UNION, and friends.
A subquery is a SELECT inside another statement. Scalar subqueries return exactly one value, IN subqueries a column, derived tables (in the FROM) an entire table.
-- Products more expensive than the average (scalar subquery)
SELECT name, preis FROM produkte
WHERE preis > (SELECT AVG(preis) FROM produkte); -- Laptop
-- Customers who have at least one order (IN)
SELECT name FROM kunden WHERE id IN (SELECT kunde_id FROM bestellungen);
-- Derived table
SELECT kategorie, schnitt
FROM (SELECT kategorie, AVG(preis) AS schnitt FROM produkte GROUP BY kategorie) AS t
WHERE schnitt > 100;Correlated subqueries refer to the outer row and are logically evaluated per row. EXISTS only checks whether there is any match at all – this is often clearer and faster than IN, especially with large sets and NOT.
-- Customers with an open order
SELECT k.name FROM kunden k
WHERE EXISTS (SELECT 1 FROM bestellungen b WHERE b.kunde_id = k.id AND b.status = 'offen');
-- Customers without an order (NOT EXISTS – NULL-safe)
SELECT k.name FROM kunden k
WHERE NOT EXISTS (SELECT 1 FROM bestellungen b WHERE b.kunde_id = k.id);Warning
NOT IN (subquery) is a trap: if the subquery contains even a single NULL, NOT IN returns no rows at all (x <> NULL is unknown). Use NOT EXISTS or filter with WHERE column IS NOT NULL.Set operations combine results with the same number of columns: UNION (removes duplicates), UNION ALL (keeps everything, faster), INTERSECT, EXCEPT (MySQL only supports both from 8.0.31; Oracle calls it MINUS).
SELECT stadt FROM kunden WHERE stadt IS NOT NULL
UNION
SELECT 'Wien'; -- Berlin, Hamburg, München, Wien (without duplicates)
SELECT name FROM kunden EXCEPT SELECT k.name FROM kunden k JOIN bestellungen b ON b.kunde_id = k.id; -- Eva