Sub topic 2
Scalar subqueries: one value from a query
This chapter assumes you can write SELECT, WHERE, and ORDER BY, use aggregate functions with GROUP BY, and read joins. It also assumes you know that comparing anything to NULL yields unknown rather than true or false. The chapter covers the simplest subquery shape: a query that produces exactly one value.
What makes a subquery scalar
A scalar subquery is a SELECT in parentheses that returns one row with one column. The database treats that single value as if you had typed a literal in its place. You can use it anywhere an expression is allowed: in a comparison, in arithmetic, in the SELECT list, or in a HAVING clause.
The examples use this small dataset. The NULL salary is deliberate.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50),
department_id INTEGER,
salary INTEGER
);
INSERT INTO employees (id, name, department_id, salary) VALUES
(1, 'Ana', 10, 5000),
(2, 'Ben', 10, 6000),
(3, 'Chloe', 20, 8000),
(4, 'Dev', 20, 4000),
(5, 'Eli', 30, NULL);The basic pattern
To find employees paid more than the company average, you need the average first. Without a subquery you would run two statements and paste the number from one into the other. A scalar subquery lets the database do both steps in one statement.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);AVG ignores NULL, so the average is (5000 + 6000 + 8000 + 4000) / 4 = 5750. The query returns Ben and Chloe. Eli is excluded because NULL > 5750 is unknown, and WHERE keeps only rows where the condition is true.
The inner query does not mention the outer query. It is self-contained, and the database can compute it once, then reuse the value for every outer row. Subqueries like this are called uncorrelated. The next chapters show the correlated kind, where the inner query depends on the current outer row.
Comparison operators and the one-row rule
A scalar subquery works with =, <>, <, <=, >, and >=. The standard way to guarantee one row is an aggregate without GROUP BY. An aggregate over a whole table always produces exactly one row, even when the table is empty.
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);This returns Chloe. If two employees tied for the top salary, both would be returned, because the subquery returns the value, not the person.
You can also combine the subquery with arithmetic:
SELECT name, salary
FROM employees
WHERE salary >= (SELECT AVG(salary) FROM employees) * 1.1;This returns employees paid at least 10 percent above the average (6325), which is only Chloe.
When the subquery returns the wrong number of rows
The database checks the result shape when it runs the query. There are three cases, and each behaves differently.
| Rows returned | Result of the subquery | What happens |
|---|---|---|
| Exactly 1 | That row's value | Works normally |
| 0 | `NULL` | No error; comparisons become unknown |
| More than 1 | None | Runtime error |
More than one row is an error
SELECT name
FROM employees
WHERE salary = (SELECT salary FROM employees WHERE department_id = 10);Department 10 has two employees, so the subquery returns two salaries. PostgreSQL reports "more than one row returned by a subquery used as an expression". MySQL reports "Subquery returns more than 1 row". Other databases word it differently.
The error is a runtime error, not a parse error. A query can pass on your test data and fail in production later, when someone adds a second row that matches. A filter like WHERE name = 'Ana' on a column with no unique constraint is a typical cause.
You have several ways to fix it, depending on what you mean:
- Collapse the rows with an aggregate such as
MAXorMIN. - Switch to
INif you want to match any of the values. The next chapter covers this. - Use
ANYorALLif you want a comparison against a set. A later chapter covers these. - Add
ORDER BYwith a row limit if you want one specific row.
Zero rows becomes NULL
SELECT name
FROM employees
WHERE salary > (SELECT salary FROM employees WHERE name = 'Nobody');No employee is named Nobody, so the subquery returns no rows. The database substitutes NULL, so the condition becomes salary > NULL, which is unknown. The query returns an empty result with no error and no warning.
This makes a silent failure possible. A typo in a filter inside the subquery produces an empty result rather than an error. If a query that should return rows returns nothing, run the subquery by itself first.
Picking a single row with ORDER BY and a limit
Sometimes you want a value from a particular row rather than an aggregate. You can force one row with a sort and a row limit.
SELECT name, salary
FROM employees
WHERE salary = (
SELECT salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 1
);This is equivalent to the MAX query above, so prefer MAX there. The ORDER BY form earns its place when you need a column that is not the sorted one, for example the name of the most recently hired employee.
Two cautions apply:
LIMITis not standard everywhere. SQL Server usesSELECT TOP 1, and Oracle 12c and later and standard SQL useFETCH FIRST 1 ROW ONLY.- If the sort key has ties, which tied row you get is not defined unless you add a tiebreaker column to the
ORDER BY.
The WHERE salary IS NOT NULL filter matters. Many databases sort NULL first in descending order, so without it the "top" row could be Eli with a NULL salary.
Scalar subqueries in other clauses
In the SELECT list
A scalar subquery can produce a computed column. Here every row shows its distance from the company average:
SELECT name,
salary,
salary - (SELECT AVG(salary) FROM employees) AS diff_from_avg
FROM employees;Eli's diff_from_avg is NULL, because NULL minus a number is NULL. A later chapter covers the correlated version of this pattern.
In HAVING
WHERE filters rows before grouping, so it cannot compare group aggregates. HAVING filters groups afterwards, and it can hold a scalar subquery:
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);Department 20 averages 6000, which is above 5750, so it is the only department returned. Department 10 averages 5500, and department 30 averages NULL.
Common mistakes
- Using
=against a subquery that can return several rows. Use an aggregate, or chooseIN,ANY, orALL. - Forgetting that an empty subquery yields
NULL. The outer query then returns nothing, silently. - Selecting more than one column.
WHERE salary > (SELECT MIN(salary), MAX(salary) FROM employees)is an error in most databases, because a scalar subquery must return a single column. - Ignoring
NULLin the data.AVG,MAX, andMINskipNULLvalues, so the scalar they produce may describe fewer rows than the table holds. CompareCOUNT(*)withCOUNT(salary)if the difference matters. - Relying on
LIMIT 1without a deterministicORDER BY. The query may return different rows on different runs.
Scalar subquery or two statements?
You could run the aggregate first in application code and pass the number into a second query. The subquery has two advantages. The value is read in the same statement, so under most isolation levels it cannot change between your two steps. It also saves a round trip. Keep the two-statement approach only when you need to reuse the value elsewhere in application logic.
Exercise
This query fails on a table where two employees share the department id 20: SELECT name FROM employees WHERE salary > (SELECT salary FROM employees WHERE department_id = 20);. Explain why it fails, then rewrite it so it returns employees paid more than the highest salary in department 20.
Show answer
The subquery returns one row per employee in department 20, so with two or more employees it returns more than one row. A scalar position such as the right side of > allows only one value, so the database raises a runtime error. Collapse the rows with an aggregate: SELECT name FROM employees WHERE salary > (SELECT MAX(salary) FROM employees WHERE department_id = 20);. An aggregate over the filtered rows always returns exactly one row. If department 20 had no employees, MAX would return NULL and the query would return no rows.
Exercise
Using the employees table from this chapter, write a query that lists each employee's name and how far their salary is below the highest salary in the company, as a column named gap_to_top. What value does Eli get, and why?
Show answer
SELECT name, (SELECT MAX(salary) FROM employees) - salary AS gap_to_top FROM employees;. The subquery returns 8000, so Ana gets 3000, Ben 2000, Chloe 0, and Dev 4000. Eli gets NULL, because his salary is NULL and arithmetic with NULL yields NULL.