Sub topic 12
Subquery or join? Choosing the clearer form
This chapter assumes you can write INNER JOIN and LEFT JOIN, use GROUP BY with aggregates, and reason about NULL and three-valued logic. It also assumes you have met IN, EXISTS, correlated subqueries, and derived tables in earlier chapters.
Many questions can be written either as a subquery or as a join. The two forms often return the same rows, but they do not always. They also differ in how clearly they say what you mean. This chapter gives you criteria for choosing.
The examples use these tables:
customers(id, name, status)orders(id, customer_id, total)employees(id, name, salary, department_id)departments(id, name)tickets(id, customer_id)
One question, two forms
Take the question "Which customers have placed at least one order over 100?" Here is the subquery form:
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 100);Here is the join form:
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.total > 100;These queries are not equivalent. A customer with three orders over 100 matches three rows in the join, so that customer appears three times. The IN form returns each customer at most once, because IN only asks whether a match exists.
The difference comes from what each form does:
- A join pairs rows. Its output has one row per matching pair.
- A semi-join test (
INorEXISTS) asks a yes/no question per outer row. Its output never has more rows than the outer table.
Fixing duplicates in the join form
You can make the join return one row per customer by adding DISTINCT:
SELECT DISTINCT c.id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.total > 100;Include the key (c.id) in the select list. If you write SELECT DISTINCT c.name, two different customers who share a name collapse into one row.
DISTINCT works, but it hides the intent. A reader sees a join and a de-duplication step, and has to work out that you only wanted a yes/no test. The IN or EXISTS form states the intent directly.
Choosing by what the result needs
The most useful rule is to ask which table the output columns come from.
- Only the outer table's columns are needed, and the other table is just a filter. Use
INorEXISTS. The query has no duplicate rows to remove, and the code reads as "keep customers where such an order exists". - Columns from both tables are needed. Use a join. A subquery in the
WHEREclause cannot expose its columns to the outerSELECT.
For example, to list each big order with the customer's name, you need both tables:
SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.total > 100;Here the multiplication is what you want, because the output is one row per order.
Finding rows with no match
The "customers with no orders" question has three common forms. They differ in how they handle NULL.
-- 1. NOT IN: breaks if orders.customer_id contains a NULL
SELECT c.name
FROM customers c
WHERE c.id NOT IN (SELECT o.customer_id FROM orders o);
-- 2. NOT EXISTS: safe with NULLs
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);
-- 3. LEFT JOIN anti-join: also safe with NULLs
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;Forms 2 and 3 return the same rows. In form 3, the LEFT JOIN keeps every customer and fills the order columns with NULL where nothing matches. The WHERE o.id IS NULL test then keeps only the unmatched customers. Test a column that can never be NULL in a real order row, such as the primary key o.id. If you test a nullable column, a matched row with a NULL in that column would be treated as unmatched.
Prefer form 2 or 3 over form 1 whenever the subquery column can contain NULL. Between 2 and 3, NOT EXISTS is usually the clearer statement of intent. The LEFT JOIN ... IS NULL form needs a comment for readers who have not seen the idiom.
Keep the filter in the right place in the join form. A condition on orders in the WHERE clause turns the LEFT JOIN into an inner join, because NULL rows fail the condition. To find customers with no order over 100, put the condition in the ON clause:
SELECT c.name
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id AND o.total > 100
WHERE o.id IS NULL;The NOT EXISTS version avoids this trap, because the filter sits naturally inside the subquery.
Comparing against an aggregate
For "employees paid above the company average", a scalar subquery is the clearest form:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);A join version needs a derived table or a cross join to bring the average alongside each row. It adds code without adding meaning.
For "above the department average", you have two reasonable choices. The correlated form:
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);And the join to a derived table, written as a CTE:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name, e.salary, da.avg_salary
FROM employees e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;Choose the join when you also want to display the average, because the correlated form does not expose it. Choose the correlated form when the average is only a filter.
Joining several one-to-many tables
A join becomes risky when you attach two independent one-to-many tables to the same parent. Suppose a customer has 3 orders and 2 tickets:
SELECT c.name, COUNT(*) AS n
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN tickets t ON t.customer_id = c.id
GROUP BY c.id, c.name;This returns 6 for that customer, because every order pairs with every ticket. The counts are inflated, and SUM(o.total) would be inflated in the same way.
Scalar subqueries in the SELECT list avoid the problem, because each one is computed separately:
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_count,
(SELECT COUNT(*) FROM tickets t WHERE t.customer_id = c.id) AS ticket_count
FROM customers c;The alternative is to aggregate each table in its own derived table and join the results on customer_id. Use a LEFT JOIN for the derived tables, or customers with no orders or tickets disappear. Use COALESCE(count, 0) to turn the missing counts into zero.
Decision guide
The table below summarizes the trade-offs.
| Situation | Preferred form | Reason |
|---|---|---|
| Filter by existence in another table | `EXISTS` or `IN` | No duplicate rows, and the intent is clear |
| Filter by absence | `NOT EXISTS` | Safe with `NULL`, unlike `NOT IN` |
| Need columns from both tables | `JOIN` | Only a join exposes both sets of columns |
| Compare with one overall value | Scalar subquery | Short and direct |
| Show a per-group aggregate next to each row | Join to derived table or CTE | The aggregate becomes a column |
| Several independent one-to-many counts | Select-list subqueries or pre-aggregation | Avoids row multiplication |
Performance
Do not choose on the assumption that one form is faster. Modern optimizers often rewrite IN, EXISTS, and some correlated subqueries into semi-joins, and may produce the same plan for the join and subquery forms. A NOT IN can be an exception, because the NULL rules limit how it can be rewritten. Write the form that is clearest and correct, then compare plans with EXPLAIN if a query is slow. Chapter 14 covers reading plans.
Exercise
A query joins customers to orders and returns each customer's name once per order. You want one row per customer who has at least one order over 100, and you do not need any order columns. Rewrite it with EXISTS.
Show answer
SELECT c.name FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.total > 100 ); EXISTS only checks that one matching order exists, so each customer appears at most once and no DISTINCT is needed.
Exercise
This query is meant to return customers with no order over 100, but it returns only customers who have no orders at all, plus none of the others. Why, and how do you fix it? SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.total <= 100 OR o.id IS NULL;
Show answer
The condition on o.total sits in the WHERE clause, and it also keeps customers whose orders are all 100 or less only if some order row exists, which is the wrong test. A customer with one small order and one large order still produces the small-order row and is returned incorrectly. Move the filter into the join and test for absence: LEFT JOIN orders o ON o.customer_id = c.id AND o.total > 100 WHERE o.id IS NULL. Equivalently, use NOT EXISTS with the total > 100 condition inside the subquery.