Sub topic 1
A quick refresher on subqueries in WHERE
Prerequisites
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, table aliases, INNER JOIN, and that NULL means a missing value. Aggregate functions such as AVG and COUNT also appear in the examples.
Subqueries in WHERE
A subquery is a SELECT nested inside another statement. In a WHERE clause, the inner query produces a value or a set of rows that the outer query tests.
A plain subquery runs once and does not depend on the outer query:
SELECT o.order_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(total)
FROM orders
);The inner query returns one number, the overall average. The outer query then keeps every order above that number.
Correlated subqueries
A correlated subquery refers to a column from the outer query. The inner query therefore depends on the current outer row, and the database evaluates it once for each outer row.
SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);The reference o.customer_id in the inner query points to the outer row. Each order is compared with the average of its own customer's orders.
EXISTS: asking whether any related row is there
EXISTS returns TRUE when its subquery returns at least one row, and FALSE otherwise. The database stops searching at the first match.
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);| Customer's orders | EXISTS result | Customer returned? |
|---|---|---|
| Two or more | TRUE | Yes |
| Exactly one | TRUE | Yes |
| None | FALSE | No |
Why the SELECT list inside EXISTS does not matter
EXISTS checks only whether rows exist. It never reads the values the inner SELECT lists. SELECT 1, SELECT *, and SELECT o.order_id all give the same result.
> Hmm, avoid block quotes. Use a callout instead:
Exercise
Exercise
Write a query that lists customers who have placed at least one order, using EXISTS.
Show answer
SELECT c.customerid, c.name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customerid = c.customer_id );