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

Subqueries in the FROM Clause (Derived Tables)

Treat a subquery as a temporary table in FROM with a required alias.

BeginnerDerived Table · FROM Subquery3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Put a query inside FROM, give it a name, and use its result like a table.

Think of it like…

Doing rough working on scrap paper before writing the final answer: the scrap paper (the derived table) exists only for this one calculation, and you give it a name so you can refer to it.

Where you’ve seen it

Customers whose total spend is over ₹50,000: SELECT c.name, t.total FROM customers c JOIN (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) t ON t.customer_id = c.id WHERE t.total > 50000;

Words you’ll hear

Derived table
A subquery in FROM whose result is used like a table.
Alias
The name given to the derived table (AS t); required in most databases.
Pre-aggregation
Grouping data in a derived table before joining it.
LATERAL
Needed if the derived table must reference other tables in the same FROM.

Visual diagram

Loading interactive diagram

Theory & example queries

What derived tables are good for

Pre-aggregation: group a large table down to the grain you need, then join, which avoids fan-out and is often faster. Filtering on computed columns: a SELECT alias or window function can't be used in the same query's WHERE, but it can in an outer query over a derived table.

Columns computed inside the derived table need names (SUM(amount) AS total) so the outer query can refer to them. A derived table is independent of the other items in the same FROM clause; to reference them, mark it LATERAL.

Filtering on a window functionQuery example
1Input dataStart from the source rows or state that the statement sees.
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  *3FROM4  (5    SELECT6      id,7      customer_id,8      amount,9      ROW_NUMBER() OVER (10        PARTITION BY11          customer_id12        ORDER BY13          amount DESC14      ) AS rn15    FROM16      orders17  ) ranked18WHERE19  rn = 1;
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/19
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
idcustomer_idamountrn
9034212501
917778901
94410522001

Note: Illustrative highest-value order for each customer; tie-breaking follows the query's ROW_NUMBER order only when an extra key is supplied.

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

Key takeaway: Use derived tables to stage work: aggregate, rank or compute, then filter or join.

Derived tables vs CTEs

A CTE (WITH t AS (…) SELECT … FROM t) does the same job, but is written before the main query and can be referenced several times. Modern optimizers (including PostgreSQL 12+) usually treat a single-use CTE and a derived table the same way, so the choice is mainly about readability.

Short, one-off steps read fine inline. Once you nest derived tables two or three levels deep, the query becomes hard to follow inside-out; converting them to a chain of named CTEs makes the logic read top to bottom.

The same query as a CTEQuery 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
1WITH2  totals AS (3    SELECT4      customer_id,5      SUM(amount) AS total6    FROM7      orders8    GROUP BY9      customer_id10  )11SELECT12  c.name,13  t.total14FROM15  customers c16  JOIN totals t ON t.customer_id = c.id17WHERE18  t.total > 50000;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/18
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
nametotal
Acme Retail184500
Northwind Services92750
Zenith Logistics61100

Note: Illustrative customer totals above the 50,000 threshold.

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

Key takeaway: Same power as a CTE; switch to CTEs when nesting gets deep.

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 step

Write the query that produces the intermediate result, such as totals per customer.

SQL at this step
1SELECT2  customer_id,3  SUM(amount) AS total4FROM5  orders6GROUP BY7  customer_id
What to watch at this step
Name
every computed column
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A derived table is a subquery in the FROM clause: SELECT … FROM (SELECT …) AS t. Its result is treated as a temporary table for that one query, so you can filter it, join it or aggregate it again. Most databases require an alias for it (PostgreSQL made the alias optional in version 16).

Why it matters: Derived tables are how you work in stages inside one query: aggregate first and then join, compute a column and then filter on it, or rank rows and keep the top ones. They're the inline cousin of CTEs, and you'll see them constantly in existing SQL.

When to reach for it

  • Pre-aggregating before a join
  • Filtering on window function results
  • Filtering on computed columns

When to avoid or be careful

  • Deeply nested derived tables
  • Forgetting the alias in databases that require it
  • Joining raw one-to-many tables when a pre-aggregated derived table avoids fan-out

Derived table vs CTE vs temporary table

Derived table
Best for: A short intermediate step used once

Strengths: Inline and self-contained.

Watch out: Hard to read when nested deeply; can't be reused in the same query.

CTE
Best for: Multi-step logic or steps used more than once

Strengths: Named, top-to-bottom readability.

Watch out: Slightly more verbose for tiny steps.

Temporary table
Best for: Large intermediate results reused across several queries

Strengths: Can be indexed and analysed.

Watch out: Extra statements and cleanup.

Interview signals & numbers to know

When this topic comes up

  • "Every derived table must have its own alias" error (MySQL)
  • "subquery in FROM must have an alias" (PostgreSQL < 16)
  • Filtering on ROW_NUMBER()
  • Pre-aggregation
  • Subquery vs CTE

Benchmarks & rules of thumb

1 -
alias per derived table (usually required)
PostgreSQL 16 -
alias became optional
1 query -
lifetime of a derived table

Common mistakes & follow-ups

Common interview mistakes

  • Leaving out the alias and getting a syntax error in MySQL or older PostgreSQL.
  • Forgetting to name SUM(amount) inside the derived table, then being unable to filter on it outside.
  • Nesting four levels of derived tables instead of writing CTEs.

Likely interviewer follow-ups

  • What's the difference between a derived table and a CTE?
  • How would you filter on a window function result?
  • Why pre-aggregate in a derived table before joining?
Interview tip: Show one pre-aggregation example and one window-filter example, and mention that CTEs do the same job more readably. That covers what derived tables are actually used for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Subqueries in the FROM Clause (Derived Tables) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Column & Row Subqueries (IN, ANY, SOME, ALL)
Next topic
Correlated Subqueries vs Non-Correlated Subqueries