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 64/ 160
04. Subqueries & Common Table Expressions (CTEs)

Correlated Subqueries vs Non-Correlated Subqueries

Distinguish independent subqueries from ones that reference outer rows.

IntermediateCorrelated · Non-Correlated3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A normal subquery is worked out once. A correlated subquery is worked out again for each row, because it uses that row's values.

Think of it like…

Non-correlated: the teacher calculates the class average once and compares every student with it. Correlated: for each student, the teacher looks up the average of that student's own section before comparing.

Where you’ve seen it

Flagging employees paid above their department's average: SELECT name FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id). The inner query depends on e.dept_id, so it's correlated.

Words you’ll hear

Non-correlated subquery
Doesn't reference the outer query; evaluated once.
Correlated subquery
References an outer column; evaluated per outer row (logically).
Scalar subquery
Returns exactly one value. More than one row is an error.
Decorrelation
The optimizer rewriting a correlated subquery into a join.

Visual diagram

Loading interactive diagram

Theory & example queries

Telling them apart

Check whether the subquery mentions a table alias from the outer query. If you could copy the subquery and run it by itself, it's non-correlated. If it refers to something like e.dept_id that only exists in the outer query, it's correlated.

EXISTS and NOT EXISTS subqueries are almost always correlated, because they ask "is there a related row for this outer row?". Scalar subqueries in SELECT or WHERE can be either, and must return at most one row or the query fails.

Company average (non-correlated)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name3FROM4  employees5WHERE6  salary > (7    SELECT8      AVG(salary)9    FROM10      employees11  );
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/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
name
Asha
Diego
Mina

Note: Illustrative employees above the company-wide average salary.

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

Key takeaway: If the subquery mentions an outer alias, it's correlated.

Performance and alternatives

Logically, a correlated subquery runs once per outer row. Modern optimizers often turn it into a join or a semi-join, but when they can't, the cost grows with outer rows times inner work. An index on the correlation column (here employees(dept_id)) is what keeps it fast.

Many correlated subqueries are clearer and faster as a window function or a join to a pre-aggregated subquery. Compute the department averages once, then compare.

Same result with a window functionQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name3FROM4  (5    SELECT6      name,7      salary,8      AVG(salary) OVER (9        PARTITION BY10          dept_id11      ) AS dept_avg12    FROM13      employees14  ) t15WHERE16  salary > dept_avg;
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.
Expected output3 sample rows
Expected output
name
Asha
Chen
Mina

Note: Illustrative employees above their own department average rather than the company-wide average.

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

Key takeaway: Index the correlation column, or replace the subquery with a window or a join.

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 inner question

Write what the subquery should compute: the overall average, or the average for one department.

SQL at this stepReadable preview
1SELECT AVG(salary)2FROM employees …
What to watch at this step
Ask
overall or per row?
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A non-correlated subquery is independent of the outer query: it could run on its own, and logically it runs once. A correlated subquery refers to a column of the outer query's current row (WHERE e2.dept_id = e.dept_id), so logically it's re-evaluated for every outer row.

Why it matters: The difference decides both what a query means and how fast it runs. "Employees who earn more than the company average" needs a non-correlated subquery; "more than their own department's average" needs a correlated one, or a window function. On large tables a correlated subquery without an index can be very slow.

When to reach for it

  • Existence checks with EXISTS / NOT EXISTS
  • Comparing each row with a value from its own group
  • Fetching one related value per row (the latest order date) when it reads more clearly

When to avoid or be careful

  • Correlated scalar subqueries in SELECT over millions of rows without an index
  • A scalar subquery that can return more than one row
  • Correlating when the question needs an overall value

Correlated subquery vs join vs window function

Correlated subquery
Best for: Per-row checks, especially EXISTS / NOT EXISTS

Strengths: Reads like the question being asked.

Watch out: Can be slow without an index if the optimizer can't decorrelate it.

Join to a grouped subquery
Best for: Comparing rows with a per-group aggregate

Strengths: Each group's aggregate is computed once.

Watch out: A little more code.

Window function
Best for: Row vs group comparisons on the same table

Strengths: One pass, no self-join, keeps every row.

Watch out: Needs an outer query to filter on the result.

Interview signals & numbers to know

When this topic comes up

  • “Above their department's average”
  • “For each row, find …”
  • EXISTS
  • "Subquery returns more than one row" error
  • A slow query with a SubPlan

Benchmarks & rules of thumb

1 -
evaluation for a non-correlated subquery
N -
logical evaluations for a correlated subquery over N rows
≤ 1 row -
allowed from a scalar subquery

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting the correlation condition and comparing every row with the company average instead of the department average.
  • Reusing the same alias inside and outside, so the "correlation" compares a column with itself.
  • Writing a scalar subquery that can return several rows and getting an error in production.

Likely interviewer follow-ups

  • How would you rewrite this correlated subquery as a join?
  • Is a correlated subquery always executed once per row?
  • How would you find each customer's most recent order date with and without a subquery?
Interview tip: State the logical behaviour (runs per outer row), then say optimizers often decorrelate it, then offer the window-function rewrite. That covers meaning, reality and the better alternative.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Correlated Subqueries vs Non-Correlated Subqueries with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Subqueries in the FROM Clause (Derived Tables)
Next topic
Performance Trade-offs: Subqueries vs Joins