Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 61/ 160
04. Subqueries & Common Table Expressions (CTEs)

Scalar Subqueries (Single Value in SELECT or WHERE)

Embed a single-value subquery in SELECT or WHERE and handle multi-row errors.

BeginnerScalar Subquery · Single Value3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Share of total revenue per productQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  product_id,3  SUM(amount) AS revenue,4  SUM(amount) / (5    SELECT6      SUM(amount)7    FROM8      order_items9  ) AS share10FROM11  order_items12GROUP BY13  product_id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Revenue share by product3 sample rows
Revenue share by product
product_idrevenueshare
12175000.4375
18125000.3125
27100000.25

Note: Sample order_items total 40,000; revenue and share change with the input rows.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Guaranteeing a single rowQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name3FROM4  customers5WHERE6  id = (7    SELECT8      customer_id9    FROM10      orders11    ORDER BY12      amount DESC,13      id14    LIMIT15      116  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Customer for the largest order1 sample row
Customer for the largest order
name
Riya Shah

Note: Assumes the largest order belongs to Riya Shah; ORDER BY id resolves ties deterministically.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns the customer behind the single largest order.

Key takeaway: Design the subquery to return one row; use IN or EXISTS for sets.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Subquery

Write the single-value question

Write a query that returns one number or value, usually an aggregate like AVG or MAX.

SQL at this step
1(2  SELECT3    AVG(price)4  FROM5    products6)
What to watch at this step
Returns
1 row, 1 column
Tip: use ← → to move between steps

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

Scalar subquery
Best for: Comparing rows with one overall value

Strengths: Simple and readable.

Watch out: Errors on multiple rows; correlated versions can be slow.

Window function (AVG() OVER ())
Best for: Showing the overall or per-group value on every row

Strengths: One pass; works per group with PARTITION BY.

Watch out: Needs an outer query to filter on it.

Join to an aggregated subquery
Best for: Per-group values over many rows

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?
Interview tip: Show the above-average example, then mention the 0-row (NULL) and 2+-row (error) cases. Those two edge cases are what interviewers listen for.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Visualizing & Debugging Complex Multi-Join Queries
Next topic
Column & Row Subqueries (IN, ANY, SOME, ALL)