Subqueries in the FROM Clause (Derived Tables)
Treat a subquery as a temporary table in FROM with a required alias.
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
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.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT *FROM ( SELECT id, customer_id, amount, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY amount DESC ) AS rn FROM orders ) rankedWHERE rn = 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| id | customer_id | amount | rn |
|---|---|---|---|
| 903 | 42 | 1250 | 1 |
| 917 | 77 | 890 | 1 |
| 944 | 105 | 2200 | 1 |
Note: Illustrative highest-value order for each customer; tie-breaking follows the query's ROW_NUMBER order only when an extra key is supplied.
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.
| 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 |
WITH totals AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id )SELECT c.name, t.totalFROM customers c JOIN totals t ON t.customer_id = c.idWHERE t.total > 50000;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output3 sample rows
| name | total |
|---|---|
| Acme Retail | 184500 |
| Northwind Services | 92750 |
| Zenith Logistics | 61100 |
Note: Illustrative customer totals above the 50,000 threshold.
Key takeaway: Same power as a CTE; switch to CTEs when nesting gets deep.
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 inner step
Write the query that produces the intermediate result, such as totals per customer.
SELECT customer_id, SUM(amount) AS totalFROM ordersGROUP BY customer_idWhen 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
Strengths: Inline and self-contained.
Watch out: Hard to read when nested deeply; can't be reused in the same query.
Strengths: Named, top-to-bottom readability.
Watch out: Slightly more verbose for tiny steps.
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?
Knowledge check
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.