Sub topic 15
Choosing between subqueries and joins
This chapter assumes you can write single-row, multi-row, correlated and EXISTS subqueries, and that you know inner and outer joins on the HR sample schema (EMPLOYEES, DEPARTMENTS). It does not introduce new syntax. It gives you criteria for picking one form over another when several would work.
Many problems have several correct answers
Oracle accepts several forms for the same question. "Which departments have at least one employee?" can be written four ways:
-- 1. Join (can duplicate rows)
SELECT d.department_name
FROM departments d
JOIN employees e ON e.department_id = d.department_id;
-- 2. Join with DISTINCT
SELECT DISTINCT d.department_name
FROM departments d
JOIN employees e ON e.department_id = d.department_id;
-- 3. IN subquery
SELECT d.department_name
FROM departments d
WHERE d.department_id IN (SELECT e.department_id FROM employees e);
-- 4. EXISTS subquery
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1 FROM employees e
WHERE e.department_id = d.department_id);Query 1 returns one row per employee, so a department with 45 employees appears 45 times. Queries 2, 3 and 4 return each department once. The choice therefore starts with correctness, not speed.
Criterion 1: do you need columns from the other table?
A subquery in WHERE only filters. It cannot return its columns to the outer query. If the result must show the employee's name next to the department name, you need a join (or a scalar subquery, see below).
| Need | Better fit |
|---|---|
| Only test whether matching rows exist | EXISTS or IN |
| Only test that no matching rows exist | NOT EXISTS |
| Show columns from both tables | Join |
| Compare to one aggregate value | Single-row subquery |
| Show an aggregate beside each detail row | Join to an inline view, or an analytic function |
Criterion 2: what happens to row counts?
A join multiplies rows when the relationship is one-to-many. A semi-join, which is what IN and EXISTS express, never does. It asks only whether at least one match exists.
- If the question is "does a match exist?", prefer EXISTS or IN. You get no duplicates and need no DISTINCT.
- If you wrote
SELECT DISTINCTonly to remove duplicates created by a join, that is a sign you wanted a semi-join. - DISTINCT also forces a sort or hash step, which a semi-join avoids.
The reverse mistake also happens. With IN, the subquery's values are only tested, so duplicates inside the subquery are harmless. With a join, they would multiply the rows.
Criterion 3: NULLs and anti-joins
For "rows with no match", the choice has a correctness side as well as a style side.
-- Employees who manage nobody: safe
SELECT e.last_name
FROM employees e
WHERE NOT EXISTS (SELECT 1
FROM employees r
WHERE r.manager_id = e.employee_id);
-- Same result with an outer join and an IS NULL test
SELECT e.last_name
FROM employees e
LEFT JOIN employees r ON r.manager_id = e.employee_id
WHERE r.employee_id IS NULL;Both forms ignore NULLs in manager_id. NOT IN does not, as the NOT IN chapter showed: one NULL in the subquery result makes the whole condition return no rows. Use NOT IN only when the subquery column is declared NOT NULL or you filter NULLs out explicitly.
In the outer-join form, test a column that is never NULL in the real table, such as the primary key. Do not test a column that could be NULL in matched rows, or you will treat matches as non-matches.
Criterion 4: aggregates next to detail rows
"Employees paid more than their department average" has three common forms.
-- Correlated subquery
SELECT e.last_name, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);
-- Join to an inline view
SELECT e.last_name, e.salary
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id) a
ON a.department_id = e.department_id
WHERE e.salary > a.avg_sal;
-- Analytic function: one pass over the table
SELECT last_name, salary
FROM (SELECT last_name, salary,
AVG(salary) OVER (PARTITION BY department_id) AS avg_sal
FROM employees)
WHERE salary > avg_sal;All three give the same rows here. The inline view computes each department's average once, which suits large tables. The analytic version reads EMPLOYEES only once. The correlated form reads most naturally, and the optimizer may rewrite it into something like the inline-view form (see below). The inline view and analytic versions also let you show avg_sal in the output, which the correlated form cannot.
Employees with a NULL department_id are dropped by all three forms, because NULL = NULL is not true. That is usually what you want here, but check it.
Criterion 5: scalar subquery or outer join in the SELECT list
-- Scalar subquery: a department with no employees shows 0
SELECT d.department_name,
(SELECT COUNT(*) FROM employees e
WHERE e.department_id = d.department_id) AS headcount
FROM departments d;
-- Outer join and GROUP BY: same result
SELECT d.department_name, COUNT(e.employee_id) AS headcount
FROM departments d
LEFT JOIN employees e ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name;The scalar subquery is easy to extend with a second aggregate, but each extra scalar subquery is another lookup per row. Oracle caches scalar subquery results by input value, so it helps when the correlation column has few distinct values. For many columns or many distinct values, one join with GROUP BY is usually cheaper.
A scalar subquery that can return more than one row fails at run time with ORA-01427. A join never raises this error. It returns the extra rows instead, which can be a silent error.
How the optimizer changes the picture
Oracle does not run your query text literally. It often rewrites it before choosing a plan, so a subquery is not automatically a row-by-row loop.
- IN and EXISTS subqueries are commonly unnested into semi-joins.
- NOT EXISTS becomes an anti-join. NOT IN can also become one, but the optimizer needs to handle NULLs (a null-aware anti-join), and it may fall back to a slower filter when it cannot.
- A correlated aggregate subquery may be merged into a join with a grouped view.
- A simple WITH query is usually inlined. Oracle may instead materialize it into a temporary table if the name is referenced more than once.
You can check what happened with the execution plan:
EXPLAIN PLAN FOR
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1 FROM employees e
WHERE e.department_id = d.department_id);
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for operations such as HASH JOIN SEMI, HASH JOIN ANTI or NESTED LOOPS SEMI. If you see a FILTER operation with a subquery below it, the subquery is being run once per outer row (with caching), not unnested.
Because of this rewriting, the fastest-looking form on paper is often not faster in practice. Do not rewrite working queries for speed without comparing plans and timings on realistic data volumes. On the small HR schema, everything is fast.
When to name a subquery with WITH
Use WITH when the same derived result is needed twice, or when a long inline view makes the main query hard to read. Oracle usually inlines a WITH query that is used once. If it is used more than once, Oracle may materialize it, but the hints that control this (MATERIALIZE and INLINE) are not officially documented, so avoid depending on them in code you must support for years.
A decision guide
Common mistakes
- Using a join for an existence test and then adding DISTINCT to hide the duplicates.
- Using NOT IN against a nullable column.
- Using a scalar subquery that can return several rows, which causes ORA-01427.
- Putting a filter on the outer-joined table in WHERE instead of in the ON clause. This turns the outer join into an inner join.
- Rewriting a readable query into a join with no measured gain.
Exercise
A report must list every department with its number of employees, including departments that have none. A colleague wrote SELECT d.department_name, COUNT(*) FROM departments d LEFT JOIN employees e ON e.department_id = d.department_id GROUP BY d.department_name. What is wrong with the result, and how do you fix it? Then name one other way to write the query.
Show answer
COUNT() counts the row produced by the outer join even when there is no matching employee, so an empty department shows 1 instead of 0. Use COUNT(e.employeeid), which ignores the NULL produced for a missing employee. Grouping by departmentid as well as department_name is also safer, because names need not be unique. Another form is a scalar subquery in the SELECT list: (SELECT COUNT() FROM employees e WHERE e.departmentid = d.departmentid) AS headcount, which returns 0 for empty departments.
Exercise
You need the names of employees who are not managers of anyone. Which of NOT IN, NOT EXISTS and LEFT JOIN with IS NULL are safe on the HR schema, and why is the third form's test column important?
Show answer
NOT EXISTS and LEFT JOIN with IS NULL are safe. NOT IN is unsafe because EMPLOYEES.MANAGERID contains a NULL for the top-level employee, so the condition returns no rows unless you add WHERE managerid IS NOT NULL to the subquery. In the LEFT JOIN form, test a column that is never NULL in a real matched row, such as r.employee_id (the primary key), so a NULL can only mean "no match".