Scalar Subqueries (Single Value in SELECT or WHERE)
Embed a single-value subquery in SELECT or WHERE and handle multi-row errors.
In plain words
A small query that gives back one number, used inside a bigger query as if it were that number.
Think of it like…
Asking one quick question in the middle of a sentence: "show me everyone taller than (the average height of the class)". The bracketed question must have exactly one answer for the sentence to make sense.
Where you’ve seen it
Products priced above the overall average: SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products); and a dashboard tile showing the latest order time: SELECT (SELECT MAX(created_at) FROM orders) AS last_order_at;
Words you’ll hear
- Scalar subquery
- A subquery returning one row and one column, used as a value.
- Empty result
- A scalar subquery with no rows evaluates to NULL.
- More than one row
- Causes an error at run time.
- Correlated scalar subquery
- References the outer row, so it's evaluated per row.
Visual diagram
Theory & example queries
Where scalar subqueries fit
Any place that expects a single value can take a scalar subquery: a comparison in WHERE or HAVING, a column in SELECT, an argument to a function, or a value in INSERT or UPDATE. Aggregates without GROUP BY (AVG, MAX, COUNT) are the safest inner queries, because they always return exactly one row.
A non-correlated scalar subquery doesn't depend on the outer row, so the database computes it once. A correlated one, such as (SELECT MAX(created_at) FROM orders o WHERE o.customer_id = c.id) in the SELECT list, is logically evaluated per outer row; with an index on the correlation column it's fine for small results, but over many rows a join to a grouped subquery is usually faster.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
SELECT product_id, SUM(amount) AS revenue, SUM(amount) / ( SELECT SUM(amount) FROM order_items ) AS shareFROM order_itemsGROUP BY product_id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Revenue share by product3 sample rows
| product_id | revenue | share |
|---|---|---|
| 12 | 17500 | 0.4375 |
| 18 | 12500 | 0.3125 |
| 27 | 10000 | 0.25 |
Note: Sample order_items total 40,000; revenue and share change with the input rows.
Key takeaway: Aggregates make safe scalar subqueries; correlated ones cost per row.
Zero rows, many rows
If the subquery returns no rows, its value is NULL, and comparisons with NULL are UNKNOWN, so WHERE price > (SELECT price FROM products WHERE id = 999) returns nothing when product 999 doesn't exist. Wrap it in COALESCE if a default makes sense.
If it returns more than one row, the query fails ("more than one row returned by a subquery used as an expression"), possibly only in production when the data changes. Make it single-valued by design: aggregate it, filter by a unique key, or use ORDER BY … LIMIT 1 when you deliberately want one of several rows. If you really mean "any of these values", use IN or EXISTS instead.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT nameFROM customersWHERE id = ( SELECT customer_id FROM orders ORDER BY amount DESC, id LIMIT 1 );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Customer for the largest order1 sample row
| name |
|---|
| Riya Shah |
Note: Assumes the largest order belongs to Riya Shah; ORDER BY id resolves ties deterministically.
returns the customer behind the single largest order.
Key takeaway: Design the subquery to return one row; use IN or EXISTS for sets.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Write the single-value question
Write a query that returns one number or value, usually an aggregate like AVG or MAX.
( SELECT AVG(price) FROM products)When to use it & trade-offs
What it is
A scalar subquery is a subquery in parentheses that returns exactly one value (one row, one column), so it can be used anywhere a single value can: in WHERE, in the SELECT list, or in calculations. WHERE price > (SELECT AVG(price) FROM products) compares every row with the overall average. If it returns no rows, the value is NULL; if it returns more than one, the query fails.
Why it matters: Comparing rows with an overall figure (above-average salaries, orders bigger than the median) is a very common question, and scalar subqueries are the simplest answer. Interviewers also check that you know the failure modes: more than one row raises an error, and per-row subqueries in SELECT can be slow.
When to reach for it
- Above- or below-average comparisons
- Share-of-total calculations
- Single summary values in dashboards
When to avoid or be careful
- Scalar subqueries that can return several rows
- Correlated scalar subqueries in SELECT over millions of rows
- Using = (SELECT …) when you mean IN (SELECT …)
Scalar subquery vs window function vs join
Strengths: Simple and readable.
Watch out: Errors on multiple rows; correlated versions can be slow.
Strengths: One pass; works per group with PARTITION BY.
Watch out: Needs an outer query to filter on it.
Strengths: Each group computed once; predictable performance.
Watch out: More code.
Interview signals & numbers to know
When this topic comes up
- “Employees earning more than the average salary”
- “more than one row returned by a subquery”
- Share of total
- Subquery in SELECT
- Comparisons with an overall figure
Benchmarks & rules of thumb
- 1 × 1
- rows × columns a scalar subquery must return
- NULL
- value when it returns no rows
- Error
- when it returns more than one row
Common mistakes & follow-ups
Common interview mistakes
- Writing WHERE customer_id = (SELECT customer_id FROM orders WHERE amount > 1000), which fails as soon as two orders qualify.
- Expecting a default value when the subquery returns no rows, and getting NULL.
- Using a correlated subquery in SELECT for every row of a large report.
Likely interviewer follow-ups
- What happens if a scalar subquery returns more than one row, or none?
- How would you find products priced above their own category's average?
- When would you replace a scalar subquery with a window function?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Scalar Subqueries (Single Value in SELECT or WHERE) with hands-on SQL practice and interview Q&A.