Sub topic 1
What a Subquery Is and Where It Can Appear
Prerequisites
This chapter assumes you can write SELECT, WHERE, and ORDER BY, use aggregate functions such as AVG and COUNT with GROUP BY, and reason about NULL values. The examples use three tables: employees(name, salary, department_id), customers(id, name), and orders(id, customer_id, total).
What a subquery is
A subquery is a SELECT statement nested inside another statement. The database runs the inner query first, then uses its result in the outer statement. A subquery can appear in these places:
WHERE, to filter rowsFROM, as a derived table- the
SELECTlist, to compute a value for each row UPDATEandDELETE, to choose which rows to change
Scalar subqueries: one value from a query
A scalar subquery returns exactly one value: one row and one column. You can compare a column to it.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The inner query returns one number, the company-wide average. If it returned more than one row, the database would raise an error.
Filtering with IN and multi-row subqueries
A multi-row subquery returns a list of values, one column across many rows. IN tests whether a value appears in that list.
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 100);NOT IN and NULL: a common trap
NOT IN breaks when the subquery can return NULL. Comparing a value with NULL yields unknown, not true, so one NULL in the list makes NOT IN return no rows at all.
SELECT c.name
FROM customers c
WHERE c.id NOT IN (SELECT o.customer_id FROM orders o);If any orders.customer_id is NULL, this query returns zero rows, even when some customers have no orders. Filter out the NULL values to make it safe:
SELECT c.name
FROM customers c
WHERE c.id NOT IN (
SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL
);Exercise
Write a query that lists the names of customers who have no orders. The query must still work when orders.customer_id contains NULL.
Show answer
SELECT c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);