Sub topic 2
Single-row subqueries
A single-row subquery is a nested query that returns at most one row and one column to the outer query. This chapter covers how to write one, which operators to pair with it, and the errors you will meet in practice.
This chapter assumes you can write SELECT, WHERE, ORDER BY and GROUP BY, use aggregate functions such as AVG and MAX, and join two tables. The examples use the Oracle HR sample schema (EMPLOYEES and DEPARTMENTS).
The working model
Oracle evaluates the inner query first, produces one value, and substitutes that value into the outer query's condition. You can read the query below as "find the average salary, then find everyone paid more than that number".
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The subquery is not correlated. It refers to no column of the outer query, so Oracle needs to run it only once. The aggregate AVG with no GROUP BY always yields exactly one row, which makes this safe.
Syntax rules
A subquery follows a few fixed rules.
- Enclose it in parentheses.
- Put it on the right-hand side of the comparison. Oracle accepts it on the left, but the right-hand form is the convention and is easier to read.
- Do not put an ORDER BY in a subquery used in a WHERE condition. It is not allowed there and would not help, because the result is a single value.
- The subquery must return one column when used with a single-value operator.
Single-row comparison operators
Single-row operators expect exactly one value on each side.
| Operator | Meaning |
|---|---|
| = | equal to |
| <> or != | not equal to |
| > | greater than |
| >= | greater than or equal to |
| < | less than |
| <= | less than or equal to |
You can use a subquery in the same way as a literal. Find the employees who work in the same department as an employee named Grant, for example. This assumes exactly one row matches that last name, which the HR schema does not guarantee. Check that assumption before you rely on it.
SELECT last_name, department_id
FROM employees
WHERE department_id = (SELECT department_id
FROM employees
WHERE employee_id = 178);Filtering on the primary key (EMPLOYEEID) is the reliable way to guarantee one row. A filter on a non-unique column such as LASTNAME is a latent bug, since a new row can break the query months later.
Subqueries in HAVING
A single-row subquery also works in the HAVING clause, where it filters groups instead of rows. This query returns the departments whose average salary exceeds 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);Here the inner and outer queries both aggregate, but at different levels. The inner query yields one company-wide number, and the outer query yields one average per department.
Combining several subqueries
A statement can hold more than one single-row subquery. Each one is evaluated independently, and the conditions combine with AND or OR as usual.
SELECT last_name, job_id, salary
FROM employees
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 141)
AND salary > (SELECT salary
FROM employees
WHERE employee_id = 143);Subqueries can also nest inside other subqueries. Oracle allows deep nesting in WHERE clauses, but more than two levels quickly becomes hard to read. Prefer a join or a WITH clause at that point.
What the subquery may return
The result of a single-row subquery falls into one of three cases, and each behaves differently.
| Rows returned | Result in the outer query |
|---|---|
| Exactly one | The value is used in the comparison. |
| Zero | The subquery yields NULL, so the comparison is unknown and no outer rows match. No error is raised. |
| More than one | Oracle raises ORA-01427: single-row subquery returns more than one row. |
The zero-row case
An empty result does not raise an error. It silently makes the condition unknown. A typo in a filter therefore produces an empty report instead of a failure.
SELECT last_name
FROM employees
WHERE salary > (SELECT salary
FROM employees
WHERE last_name = 'Nobody');This returns no rows. It runs successfully, and it is easy to mistake for "no employee earns more".
The too-many-rows case
ORA-01427 is the most common subquery error. It tends to appear after the data changes, since a query that worked while a filter matched one row fails when a second row appears.
SELECT last_name
FROM employees
WHERE salary = (SELECT MIN(salary)
FROM employees
GROUP BY department_id);This fails with ORA-01427 because GROUP BY produces one minimum per department. You have three ways to fix it, and the right one depends on what you meant.
- Remove the GROUP BY if you wanted the single company-wide minimum.
- Switch to IN, ANY or ALL if you wanted to compare against the set of values. The next chapter covers these.
- Add a correlation to the outer query if you wanted each employee compared with their own department's minimum. That is a correlated subquery, covered later in the tutorial.
If you really do want one row from a set, make the choice explicit.
SELECT last_name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);An aggregate with no GROUP BY is guaranteed to return exactly one row, even over an empty table. That guarantee makes aggregates the safest source for a single-row subquery. Note that over an empty table, AVG, MAX and MIN return NULL while COUNT returns 0.
NULL in the returned value
A subquery can return exactly one row whose value is NULL. This happens when every row in the group has a NULL in that column. The comparison then evaluates to unknown, and no outer rows match, just as in the zero-row case.
SELECT last_name
FROM employees
WHERE commission_pct > (SELECT AVG(commission_pct)
FROM employees
WHERE department_id = 10);If no employee in department 10 has a commission, AVG returns NULL and the query returns nothing. Wrap the inner expression in NVL when a default makes sense for your problem.
SELECT last_name
FROM employees
WHERE NVL(commission_pct, 0) > (SELECT NVL(AVG(commission_pct), 0)
FROM employees
WHERE department_id = 10);Whether a default is correct is a business decision. Treating a missing commission as zero is reasonable here, but not for every column.
Subqueries outside WHERE
A single-row subquery that returns one column can sit wherever Oracle accepts an expression. It can appear in the SELECT list and in the HAVING clause, among other places. When it appears in the SELECT list, it is called a scalar subquery, and a later chapter treats it in detail. A short example shows the idea.
SELECT last_name,
salary,
salary - (SELECT AVG(salary) FROM employees) AS diff_from_avg
FROM employees;Oracle runs the uncorrelated subquery once and reuses the value for every row.
Common mistakes
- Using = with a subquery that can return several rows. Use IN, or aggregate to one row.
- Filtering on a non-unique column and assuming one match.
- Returning two columns. A single-value comparison with a two-column subquery fails with ORA-00913: too many values.
- Forgetting that an empty result gives no error, only no rows.
- Comparing with a NULL result and expecting a match.
Check your understanding
Exercise
The query SELECT lastname FROM employees WHERE salary > (SELECT salary FROM employees WHERE departmentid = 50) fails with ORA-01427. Give two different ways to fix it, and say what each one means.
Show answer
Department 50 has many employees, so the subquery returns many salaries. Fix 1: aggregate to a single value, for example (SELECT MAX(salary) FROM employees WHERE department_id = 50), which returns employees paid more than the top earner of department 50. Fix 2: keep the multi-row subquery and use ALL or ANY instead of >, for example salary > ALL (...), which has the same meaning as MAX, or salary > ANY (...), which has the same meaning as MIN.
Exercise
Write a query that returns the employees whose salary is below the company-wide average, and name the one situation where it returns no rows even though no error occurs.
Show answer
SELECT last_name, salary FROM employees WHERE salary < (SELECT AVG(salary) FROM employees); It returns no rows when the subquery yields NULL, which happens if EMPLOYEES is empty or every SALARY is NULL, because the comparison is then unknown for every row.