Learn SQL
-- subqueries.scalar_subquery

Scalar Subqueries in SQL

A query that returns one value, used where a value goes

--concept

A scalar subquery is a SELECT inside parentheses that returns a single row and column — one value. Because it IS a value, you can drop it into comparisons, SELECT lists and CASE expressions: WHERE salary > (SELECT AVG(salary) FROM employees). The inner query runs (conceptually) first, its single value substitutes into the outer query, and the outer WHERE evaluates against it.

--how it works
1

Write the inner query standalone

SELECT AVG(salary) FROM employees — run it alone first: it must return exactly one row, one column to be a scalar.

2

Substitute it where a value goes

Wrap in parentheses and place it in a comparison, SELECT list or CASE: WHERE salary > (…).

3

The engine folds it in

Most plans evaluate the inner query once (an InitPlan), then treat its value as a constant for the outer scan.

4

The outer query compares against it

Each employee row is tested against the folded constant — above-average filtering with no magic number in the code.

5

Guard the one-row contract

If the inner query could return zero or many rows, wrap it: MAX(…), MIN(…), or add LIMIT 1 — the query errors otherwise.

--visualization
employeesAlice85,000Bob52,000Cynthia91,000David47,000Elena58,000Farid73,000SELECT AVG(salary) FROM employeesrunning accumulator — SUM over 6 rows…inner query starts — must return exactly one valueWHERE salary > (SELECT AVG(salary) …)the engine evaluates the innermost query first
kept (above average) filtered out substituted value
Stage 1 / 4
The inner query runs first: SELECT AVG(salary) FROM employees — a scalar subquery, exactly one value.
--example
query.sql
1SELECT name, salary
2FROM employees
3WHERE salary > (SELECT AVG(salary) FROM employees);
Result
namesalary
Alice85000
Cynthia91000
Farid73000

The inner query computes the average across all six employees (67,666.67). That single number then acts as a constant in the outer WHERE, keeping only the three higher earners. One query, two layers, zero magic numbers.

--variants

Above-average earners

The canonical compare-everyone-to-the-average query.

query.sql
1SELECT name, salary
2FROM employees
3WHERE salary > (SELECT AVG(salary) FROM employees);
Result
namesalary
Alice85000
Cynthia91000
Farid73000
1Inner: AVG over six salaries = 67,666.67.
2Outer: three salaries exceed it — Alice, Cynthia, Farid.
3Hard-coding 67,666.67 would rot as data changes; the subquery never does.

Scalar subquery in the SELECT list

Annotate each row with a value computed elsewhere.

query.sql
1SELECT name, salary,
2 (SELECT AVG(salary) FROM employees) AS company_avg,
3 salary - (SELECT AVG(salary) FROM employees) AS vs_avg
4FROM employees WHERE department = 'Sales';
Result
namesalarycompany_avgvs_avg
Bob5200067666.67-15666.67
Elena5800067666.67-9666.67
1The same inner query runs (once, in real plans) and its value is stamped onto every output row.
2vs_avg turns the number into a comparison — Bob is 15,666.67 below company average.
3Columns from the outer row can also appear inside the subquery — that is the correlated case.

The one-row rule, violated

A scalar spot demands exactly one value.

query.sql
1SELECT name
2FROM employees
3WHERE salary = (SELECT salary FROM employees WHERE department = 'Sales');
Result
error
ERROR: more than one row returned by a subquery used as an expression
1Sales has two employees with different salaries — the scalar slot receives two values.
2The engine refuses at runtime; the query is not valid against this data.
3Intent decides the fix: IN (list), MAX(salary), or add a column filter that pins one row.

MAX/MIN guards — latest event per entity

A robust pattern that never violates the one-row rule.

query.sql
1SELECT * FROM orders o
2WHERE o.placed_at = (SELECT MAX(placed_at) FROM orders i WHERE i.customer_id = o.customer_id);
3-- correlated, but MAX guarantees one value
Result
order_idcustomerplaced_at
#102Elena2026-08-30
#101Bob2026-08-28
1For each order, the inner MAX finds that customer’s latest timestamp.
2Only rows equal to their customer’s latest survive — the most recent order per customer.
3MAX/LIMIT make the scalar contract unbreakable, at the cost of per-row evaluation.
--key facts
Exactly-one rulezero rows or two rows is a runtime error — wrap with MAX() or LIMIT 1 to be safe
Reads bottom-upcover the inner query alone; it must make sense as a standalone SELECT
Reuse the patternabove/below average, latest order date, next review date — same shape every time
--use cases
Above/below-average comparisons that adapt as data changes
Header fields in reports: company average, max date, total count as a column
Latest-record lookups with MAX() as a guard
Configuration lookups: (SELECT threshold FROM settings WHERE key = 'salary_floor')
--under the hood
Uncorrelated scalar subqueries usually execute once as InitPlans and cost almost nothing.
Correlated ones may run per row — check the plan for a SubPlan node; a JOIN rewrite often pays for itself.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.