Sub topic 1
What a subquery is
Prerequisites
This chapter assumes you can already do the following:
- Write basic
SELECT,WHERE,ORDER BYandGROUP BYqueries. - Join two tables.
- Use aggregate functions such as
AVG,COUNTandMAX. - Read the Oracle HR sample schema, in particular the
EMPLOYEESandDEPARTMENTStables.
All examples use the HR schema. The columns used here are employee_id, first_name, last_name, salary, manager_id and department_id in EMPLOYEES, and department_id and department_name in DEPARTMENTS.
The idea
A subquery is a SELECT statement nested inside another SQL statement. The statement that contains it is the outer query, or parent query. The nested one is the inner query.
Subqueries solve problems that need two steps. For example, "Which employees earn more than the company average?" has two parts:
- Find the company average salary.
- Find the employees whose salary is above that number.
Without subqueries you would run the first query, copy the number, and paste it into the second. A subquery lets Oracle do both in one statement, and the number is never hard-coded.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The inner query SELECT AVG(salary) FROM employees produces a single value. The outer query then uses that value as if you had typed the number yourself.
Syntax rules
A subquery follows a few fixed rules:
- It is enclosed in parentheses.
- It must be a complete
SELECTstatement, with its ownSELECTandFROM. - In a
WHEREcondition, it is normally placed on the right-hand side of the comparison operator. This is a readability convention, not a requirement. - It cannot end with a semicolon inside the parentheses. Only the whole statement ends with one.
- An
ORDER BYis not allowed in a subquery in aWHEREclause. It is allowed in an inline view in theFROMclause, and it is required when you combine it with a row limit such asFETCH FIRST.
Oracle allows subqueries to be nested up to 255 levels in the WHERE clause. In practice, more than two or three levels is a sign that you should restructure the query, for example with a join or a WITH clause, which later chapters cover.
How Oracle evaluates a simple subquery
For a subquery that does not refer to the outer query, the logical order is:
- Oracle runs the inner query.
- Oracle passes its result to the outer query.
- The outer query finishes using that result.
This describes the meaning of the statement. The optimizer is free to execute it differently, as long as the result is the same. A later chapter covers how it does that.
A subquery of this kind is called an uncorrelated subquery, or non-correlated subquery. It is self-contained. You could copy it out and run it alone. A correlated subquery, which refers to a column of the outer query, cannot run alone. That is a separate chapter.
What a subquery can return
The shape of the result decides which operators you can use. This is the most important thing to learn about subqueries.
| Shape of the result | Name | Typical operators |
|---|---|---|
| One row, one column | Single-row (or scalar) subquery | `=`, `<>`, `<`, `>`, `<=`, `>=` |
| Many rows, one column | Multi-row subquery | `IN`, `NOT IN`, `ANY`, `ALL` |
| One or more rows, several columns | Multi-column subquery | `IN` with a column list |
| Any rows (only the existence matters) | Existence test | `EXISTS`, `NOT EXISTS` |
If the shape does not match the operator, Oracle raises an error. The best-known case is a single-row operator used with a subquery that returns more than one row:
SELECT last_name
FROM employees
WHERE salary = (SELECT salary
FROM employees
WHERE department_id = 30);Department 30 has several employees, so the subquery returns several rows. Oracle stops with ORA-01427: single-row subquery returns more than one row. The fix is to use a multi-row operator such as IN, or to change the subquery so that it returns one row.
The opposite case is not an error. If a single-row subquery returns no rows, Oracle treats the result as NULL. A comparison with NULL is never true, so the outer query returns no rows. That can look like a correct empty answer when it is actually a mistake in the inner query, such as a typo in a filter value.
A second example: returning a set
Sometimes the inner query returns a list, and you want to know whether a value is in it. The query below finds the names of departments that have at least one employee earning more than 10000.
SELECT department_name
FROM departments
WHERE department_id IN (SELECT department_id
FROM employees
WHERE salary > 10000);The inner query returns a set of department IDs, possibly with duplicates. IN tests whether the outer department_id appears in that set. Duplicates in the set do not produce duplicate rows in the outer result. This is a difference from a join, where an employee-level match would repeat the department once per matching employee unless you add DISTINCT.
Where subqueries can appear
A subquery can be placed in several clauses of a statement:
| Location | Role of the subquery | Covered in |
|---|---|---|
| `WHERE` | Supplies a value or a set for a condition | This chapter and the next two |
| `HAVING` | Supplies a value or a set for a group-level condition | Placement chapter |
| `FROM` | Acts as a temporary table, called an inline view | Inline views chapter |
| `SELECT` list | Supplies one value per row, called a scalar subquery | Scalar subqueries chapter |
| `INSERT`, `UPDATE`, `DELETE` | Chooses rows or supplies values | DML chapter |
This chapter focuses on WHERE, because it is the simplest place to see how the nesting works.
A subquery in HAVING
A short example shows that the same idea works at the group level. This query lists departments whose average salary is above the company-wide average.
SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);The subquery here is evaluated for the whole table, and the HAVING clause compares each group's average with the result. You cannot write this condition in WHERE, because WHERE runs before grouping and cannot use an aggregate of the group.
Subqueries compared with joins
Many subqueries can be rewritten as joins, and the reverse is also true. The first example, for instance, could be written as a join against an inline view that holds the average. The two forms are not always equivalent, so the choice is not purely style.
- A subquery keeps each outer row at most once, because it only filters. A join can multiply rows when the match is one-to-many.
- A subquery in
WHEREcannot add columns from the inner table to the output. A join can. - Some questions read more naturally as subqueries, such as "greater than the average" or "has no matching rows".
Oracle's optimizer often transforms one form into the other internally, so you should not assume that a join is always faster. The final chapter returns to this decision.
Common mistakes
- Forgetting the parentheses around the subquery. Oracle reports a syntax error such as
ORA-00936: missing expressionorORA-00907: missing right parenthesis. - Using
=where the subquery can return several rows, which causesORA-01427. - Selecting more than one column in a subquery used with a single-column comparison. This raises
ORA-00913: too many values. - Putting
ORDER BYin aWHEREsubquery. Oracle reportsORA-00907: missing right parenthesis. - Using an aggregate in the outer
WHEREinstead of a subquery orHAVING. Oracle reportsORA-00934: group function is not allowed here.
Summary
A subquery is a complete SELECT nested in parentheses inside another statement. The simple kind runs independently of the outer query and returns a value or set that the outer query uses. The number of rows and columns it returns determines which operators are valid, and a mismatch is the source of most beginner errors, especially ORA-01427. The following chapters cover each shape in turn.
Exercise
The query SELECT last_name FROM employees WHERE department_id = (SELECT department_id FROM departments WHERE location_id = 1700); fails with ORA-01427 in the HR schema. Why does it fail, and how would you change the query so that it works?
Show answer
Several departments are located at location 1700, so the subquery returns more than one row, and = accepts only one value. Replace = with IN: WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = 1700).
Exercise
You want departments whose average salary is higher than the company average. Why can't you write WHERE AVG(salary) > (SELECT AVG(salary) FROM employees) in the outer query, and what clause should you use instead?
Show answer
WHERE filters individual rows before grouping, so a group function is not allowed there (ORA-00934). Use GROUP BY department_id together with HAVING AVG(salary) > (SELECT AVG(salary) FROM employees).