Sub topic 6
Scalar subqueries in the SELECT list
This chapter assumes you can write basic SELECT, WHERE, GROUP BY and join queries. It also assumes you know the aggregate functions AVG, COUNT and MAX, and that you have met single-row subqueries and correlated subqueries. All examples use the Oracle HR sample schema (EMPLOYEES and DEPARTMENTS).
What a scalar subquery is
A scalar subquery is a subquery that returns exactly one column and at most one row. Oracle treats the result as a single value. If the subquery returns no rows, the value is NULL. If it returns more than one row, Oracle raises an error.
Because it behaves like a single value, a scalar subquery can appear almost anywhere an expression can. This chapter focuses on the SELECT list, where it adds a computed column to each row of the outer query.
SELECT first_name,
last_name,
salary,
(SELECT ROUND(AVG(salary)) FROM employees) AS company_avg
FROM employees;The subquery has no reference to the outer query, so it is uncorrelated. Oracle evaluates it once and repeats the value on every row.
The three rules
A scalar subquery in the SELECT list must satisfy these rules:
- It must return exactly one column.
- It must return at most one row for each outer row.
- It must be enclosed in its own parentheses, and it is usually given an alias.
If it returns zero rows, the column shows NULL. This is the main difference from a join: a scalar subquery never removes an outer row. It can only produce NULL.
A correlated scalar subquery
Scalar subqueries are most useful when they refer to the outer row. The following query shows the number of employees in each department:
SELECT d.department_name,
(SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) AS headcount
FROM departments d;For each row of DEPARTMENTS, the inner query counts the employees whose department matches d.department_id. The reference to d makes it correlated.
Departments with no employees appear with a headcount of 0. COUNT(*) returns 0 over an empty set, so the result is a number and not NULL. Other aggregates behave differently:
SELECT d.department_name,
(SELECT MAX(e.salary)
FROM employees e
WHERE e.department_id = d.department_id) AS top_salary
FROM departments d
ORDER BY d.department_name;For a department with no employees, MAX returns NULL. An aggregate without a GROUP BY always returns exactly one row, so these subqueries never fail with "too many rows".
Several scalar subqueries in one query
Each scalar subquery returns one column, so you need one subquery for each value you want:
SELECT d.department_name,
(SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) AS headcount,
(SELECT ROUND(AVG(e.salary))
FROM employees e
WHERE e.department_id = d.department_id) AS avg_salary
FROM departments d;This works, but it scans EMPLOYEES once per subquery for each department, at least in the naive execution model. If you need many values from the same table, an inline view with GROUP BY joined to DEPARTMENTS is usually clearer and often faster. The inline view is covered in the previous chapter.
SELECT d.department_name, s.headcount, s.avg_salary
FROM departments d
LEFT JOIN (SELECT department_id,
COUNT(*) AS headcount,
ROUND(AVG(salary)) AS avg_salary
FROM employees
GROUP BY department_id) s
ON s.department_id = d.department_id;The LEFT JOIN keeps departments with no employees. Their headcount is NULL here, whereas the scalar subquery version returned 0. You can use NVL(s.headcount, 0) to match.
Looking up a value from another table
A common use is a lookup: fetching one descriptive value for each row. The query below shows each employee with the name of their department:
SELECT e.last_name,
(SELECT d.department_name
FROM departments d
WHERE d.department_id = e.department_id) AS department_name
FROM employees e;This is safe because DEPARTMENTID is the primary key of DEPARTMENTS, so at most one row can match. An employee with no department (DEPARTMENTID is NULL) gets a NULL name. This is the same result an outer join would give.
If the lookup column were not unique, the subquery could return several rows for one employee and the query would fail with ORA-01427.
Error: ORA-01427
The error message is "ORA-01427: single-row subquery returns more than one row". It appears when a scalar subquery produces more than one row for some outer row.
-- Fails: a department has many employees, so the subquery returns many rows.
SELECT d.department_name,
(SELECT e.last_name
FROM employees e
WHERE e.department_id = d.department_id) AS employee
FROM departments d;Oracle raises the error only when it actually meets such a row. A query can run correctly for months and then fail after new data is added. To guard against this, do one of the following:
- Aggregate the values so exactly one row returns, for example with MAX, MIN or LISTAGG.
- Add a condition that guarantees uniqueness, such as a primary key comparison.
- Limit the rows with
FETCH FIRST 1 ROW ONLYafter an ORDER BY.
SELECT d.department_name,
(SELECT e.last_name
FROM employees e
WHERE e.department_id = d.department_id
ORDER BY e.salary DESC
FETCH FIRST 1 ROW ONLY) AS top_earner
FROM departments d;This form requires Oracle Database 12c or later. Note that if two employees share the highest salary, only one is returned, and which one is not guaranteed unless you add a tie-breaking column to the ORDER BY.
Scalar subqueries elsewhere in the statement
Although this chapter centers on the SELECT list, a scalar subquery can also appear in:
- WHERE and HAVING, as in
salary > (SELECT AVG(salary) FROM employees). - ORDER BY, to sort by a value computed per row.
- The SET clause of an UPDATE, to assign a looked-up value.
- The VALUES list of an INSERT.
A scalar subquery cannot be used as the default value of a column, in a CHECK constraint, or in the RETURNING clause. It also cannot appear in a GROUP BY clause in some forms. When in doubt, test the statement or consult the Oracle SQL Language Reference for your version.
Here is one use in ORDER BY:
SELECT d.department_name
FROM departments d
ORDER BY (SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) DESC;Performance and caching
Oracle has an optimization called scalar subquery caching. For a correlated scalar subquery, Oracle remembers recent pairs of input value and result in a small in-memory cache. If the same correlation value comes up again, it reuses the stored result instead of running the subquery again.
This has practical consequences:
- If the outer query has few distinct correlation values (such as 27 departments over 100,000 rows), the subquery runs only about as many times as there are distinct values, and the cost is low.
- If the correlation values are almost all distinct, the cache helps little, and the subquery runs about once per outer row. Without an index on the correlated column, each run can scan the whole inner table.
- The cache has a limited size, and collisions can cause some values to be evaluated more than once.
You can also use caching deliberately to avoid repeated calls to a PL/SQL function. Wrapping the call as (SELECT my_function(col) FROM dual) lets Oracle cache the result for repeated inputs.
SELECT e.last_name,
(SELECT TO_CHAR(e.hire_date, 'YYYY') FROM dual) AS hire_year
FROM employees e;This example only shows the syntax. TO_CHAR is cheap, so wrapping it gains nothing. The technique pays off only for expensive deterministic functions.
For the correlated lookups in this chapter, an index on EMPLOYEES.DEPARTMENT_ID makes each execution an index lookup instead of a table scan. The optimizer can also rewrite some subqueries as joins, which is covered in a later chapter. Check the actual plan with EXPLAIN PLAN instead of assuming.
Scalar subquery or join?
| Situation | Better choice |
|---|---|
| One value per outer row, looked up by a unique key | Scalar subquery or outer join, both work |
| Several values from the same inner table | Inline view with GROUP BY, joined |
| You must keep every outer row, with NULL when nothing matches | Scalar subquery or LEFT JOIN |
| Many distinct outer values and no index on the inner column | Join, or add an index |
| Few distinct outer values | Scalar subquery is cheap because of caching |
Summary
- A scalar subquery returns one column and at most one row, and it works as a single value.
- Zero rows give NULL, but COUNT gives 0 because it always returns a row.
- More than one row raises ORA-01427, sometimes only after the data changes.
- A scalar subquery never removes outer rows.
- Several values from one table are usually better served by an inline view.
Exercise
Write a query that lists each department name and the last name of its highest-paid employee, using a scalar subquery in the SELECT list. Departments with no employees must still appear. Which two details make the subquery safe against ORA-01427?
Show answer
SELECT d.departmentname, (SELECT e.lastname FROM employees e WHERE e.departmentid = d.departmentid ORDER BY e.salary DESC, e.lastname FETCH FIRST 1 ROW ONLY) AS topearner FROM departments d; Two details guard the query. FETCH FIRST 1 ROW ONLY limits the result to one row, and the extra e.lastname in the ORDER BY makes the choice deterministic when salaries tie. Departments with no employees return NULL in topearner and still appear, because a scalar subquery cannot remove outer rows.
Exercise
A query uses (SELECT COUNT(*) ...) as a scalar subquery and shows 0 for empty departments. A colleague rewrites it with a LEFT JOIN to an inline view and now sees NULL for those departments. Why does the result differ, and how do you restore 0?
Show answer
COUNT(*) in a scalar subquery always returns one row, with value 0 when nothing matches. In the LEFT JOIN version, a department with no match in the inline view gets NULL for every column from that view. Wrap the column with NVL(s.headcount, 0) or COALESCE(s.headcount, 0) to restore 0.