Sub topic 4
Where Subqueries Can Appear
This chapter assumes you can write basic SELECT, WHERE, GROUP BY and ORDER BY clauses, join two tables, and use aggregates such as AVG, COUNT and MAX. Examples use the Oracle HR sample schema (EMPLOYEES and DEPARTMENTS).
A subquery is a SELECT statement nested inside another statement. Oracle accepts one in several clauses, and each position puts different limits on what the subquery may return. This chapter maps those positions and the rules for each.
The four query positions
Four clauses of a SELECT statement can hold a subquery.
| Clause | What the subquery produces | Typical use |
|---|---|---|
| WHERE | A value or a set of values to compare against | Filter rows |
| HAVING | A value or a set of values to compare against aggregated groups | Filter groups |
| FROM | A row source, called an inline view | Pre-aggregate or pre-filter data, then join it |
| SELECT list | One value per outer row, called a scalar subquery | Add a computed column |
The position decides the shape the subquery must have. A WHERE subquery used with = must return one row and one column. A FROM subquery can return any number of rows and columns, because it behaves like a table. A SELECT-list subquery must return one column and at most one row.
Subqueries in the WHERE clause
This is the most common position. The subquery runs first, and the outer query uses its result in a condition.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The subquery returns one number, so the comparison operator > is valid. If it could return more than one row, you would switch to IN, ANY or ALL, as covered in the previous chapter.
SELECT department_name
FROM departments
WHERE department_id IN (SELECT department_id
FROM employees
WHERE salary > 10000);Here the subquery returns a set of department IDs, and IN tests membership.
Subqueries in the HAVING clause
WHERE filters individual rows before grouping. HAVING filters groups after aggregation. A subquery in HAVING lets you compare a group's aggregate with a value computed elsewhere.
SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);The subquery runs once and returns the company-wide average. The outer query keeps only departments whose average exceeds it. A subquery in HAVING follows the same rules as one in WHERE: use =, > and similar operators for a single row, and IN, ANY or ALL for several rows.
Subqueries in the FROM clause
A subquery in the FROM clause is an inline view. The database treats its result as a temporary table that exists only for the duration of the statement. You must give it an alias if you want to refer to its columns from outside, and any computed column needs an alias too.
SELECT d.department_name, s.avg_sal
FROM departments d
JOIN (SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id) s
ON s.department_id = d.department_id;Without the alias avg_sal, the outer query would have no name to use for the average. Oracle does not use AS for table aliases, so write s, not AS s, after the closing parenthesis. Column aliases may use AS.
Inline views are useful when you must aggregate first and then combine the result with other data. They are also the standard way to apply an ORDER BY and a row limit before another operation.
Subqueries in the SELECT list
A subquery in the SELECT list is a scalar subquery. It must return exactly one column. It may return zero rows, in which case its value is NULL, but it must not return more than one row.
SELECT d.department_name,
(SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) AS headcount
FROM departments d;This subquery refers to d.department_id from the outer query, so it is also correlated. Oracle evaluates it for each row of DEPARTMENTS. COUNT always returns one row, which makes it safe here. A departments row with no employees gets a headcount of 0.
If the subquery could return two rows for some outer row, Oracle stops with an error.
SELECT d.department_name,
(SELECT e.last_name
FROM employees e
WHERE e.department_id = d.department_id) AS employee_name
FROM departments d;Most departments have several employees, so this statement fails with ORA-01427: single-row subquery returns more than one row. The fix is to make the subquery return one row, for example with an aggregate such as MAX or with FETCH FIRST 1 ROW ONLY, or to use a join instead.
Other places a subquery can appear
Subqueries are not limited to SELECT statements as the outer query.
- In INSERT, a subquery can supply the rows to insert (
INSERT INTO ... SELECT). - In UPDATE, a subquery can appear in the SET clause or in the WHERE clause.
- In DELETE, a subquery can appear in the WHERE clause.
Later chapters cover these statements. The placement rules stay the same: the shape of the subquery must match what the surrounding clause expects.
Oracle also allows a scalar subquery in some other expression contexts, such as CASE expressions, the ORDER BY clause and function arguments. Oracle does not allow one in a few places, for example in a CHECK constraint or as the default value of a column.
Choosing a position
When you have a problem, ask what the intermediate result looks like, and then pick the position that fits it.
- If the intermediate result is a single value or a list used to filter rows, use WHERE.
- If it filters groups on an aggregate, use HAVING.
- If you need several columns from the intermediate result, or you need to join to it, use FROM.
- If you need one extra column per outer row, use the SELECT list, and confirm that the subquery cannot return more than one row.
A scalar subquery in the SELECT list is evaluated per outer row. With many outer rows and a heavy subquery, a join to an inline view that aggregates once is often faster. Later chapters return to this trade-off.
Common errors
| Error or symptom | Cause | Fix |
|---|---|---|
| ORA-01427: single-row subquery returns more than one row | A subquery used with `=`, `>` or in the SELECT list returned several rows | Use IN, ANY or ALL, or make the subquery return one row |
| ORA-00936: missing expression | A subquery was written without a complete SELECT, or a closing parenthesis is missing | Check the parentheses and the select list |
| ORA-00904: invalid identifier | The outer query referred to a column that the inline view does not expose, or to an unaliased expression | Alias every computed column in the inline view |
| ORA-00913: too many values | The subquery returns more columns than the comparison expects | Match the number of columns on both sides |
Exercise
Write a query that lists the departments (department_id and the average salary) whose average salary is below the company-wide average. Which clause holds the subquery, and why can you use the < operator?
Show answer
SELECT departmentid, AVG(salary) AS avgsal FROM employees GROUP BY department_id HAVING AVG(salary) < (SELECT AVG(salary) FROM employees); The subquery is in the HAVING clause because the condition depends on a group aggregate. The < operator is valid because the subquery returns exactly one row and one column.
Exercise
The query SELECT d.departmentname, (SELECT e.salary FROM employees e WHERE e.departmentid = d.department_id) AS sal FROM departments d fails with ORA-01427. Rewrite it so it returns the highest salary of each department.
Show answer
SELECT d.departmentname, (SELECT MAX(e.salary) FROM employees e WHERE e.departmentid = d.department_id) AS sal FROM departments d; MAX is an aggregate, so the subquery always returns one row per outer row. Departments with no employees get NULL.