Module 3 › Session 25 · Subqueries II: Derived Tables in FROM

Subqueries II: Derived Tables in FROM

Master inline virtual relations in memory, mandatory table aliases, grain normalization, fan-out elimination, and multi-grain sibling derived table joins.

Jo class mein bola, yahan nukte mein likha hai.
What I said in class, written here as key points.

← All NukteSELECT * FROM TheShiraverse
MODULE 03 • SESSION 25 • TOPIC 28

Subqueries II: Derived Tables in FROM

Virtual Relations in Memory, Grain Normalization & Fan-Out Elimination
23
Interactive Scenes
4
Visual Studios
4
Arena Challenges
8
Interview Scenarios
Core Focus: Virtual Inline Relations, The Mandatory AS Alias Law, Defending Against Fan-Out & CTE Refactoring
✓ Verified on PostgreSQL 18

Welcome to Session 25

Today we master derived tables in the FROM clause: turning subqueries into on-the-fly virtual tables and defending against fan-out data corruption.

Today's Agenda — The Virtual Relation Blueprint

A structured four-pillar journey from inline virtual views to fan-out elimination and multi-grain synthesis.

PILLAR 01
📄 Virtual Tables in FROM
01Inline View Architecture
02The Mandatory Alias Law
03Scope & Table Lifecycles
PILLAR 02
🛡️ Grain & Fan-Out Defense
04Cartesian Child Hazards
05Pre-Aggregation Pattern
06Clean 1:1 Joined Grains
PILLAR 03
🔗 Sibling Derived Joins
07Multi-Grain Metric Synthesis
08Decoupled Operational Queries
09Variance & Productivity Gaps
PILLAR 04
🎯 Practice & Next
10Stepping Stone to CTEs
11Practice Arena: 4 Challenges
12Next: Correlated & EXISTS
💡
Why this matters: Joining child tables directly without pre-aggregation causes silent row multiplication (fan-out) that corrupts executive dashboards. Derived tables normalize metric grains before joins occur.

Teaching Anchor

Emphasize: Derived tables are the single most important architectural tool for preventing financial calculation bugs in multi-table queries.

Where We Left Off — The Scalar & Multi-Row Baseline

In Session 24, we learned how to nest queries in WHERE and SELECT. Today we nest queries in the FROM clause.

📦 SESSION 24 • COMPLETED

What Scalar & IN Solved

-- Session 24: Dynamic aggregate benchmark in WHERE
SELECT order_id, net_total FROM sales.orders
WHERE net_total > (
SELECT AVG(net_total) FROM sales.orders
);
Last class, we mastered single-cell scalar subqueries and multi-row IN membership. We learned how InitPlans cache uncorrelated aggregate values and how to guard against 3VL NULL poisoning.
✓ Scalar subqueries provide dynamic values for filtering and projection
⚠️ SESSION 25 • THE MISSION

Why We Need Subqueries in FROM

-- The fan-out explosion trap:
SELECT o.order_id, SUM(p.amount)
FROM orders o
JOIN order_items i ON o.order_id = i.order_id
JOIN payments p ON o.order_id = p.order_id;
⚠️ Items × payments Cartesian product inflates payment sums!
When you join two child tables directly, rows multiply exponentially. Derived tables allow us to pre-aggregate items and payments separately before joining to the order header.
📄 Today: Pre-aggregate grain in FROM before joining physical relations
🛡️
The Architectural Leap: A subquery in WHERE calculates a filter value. A subquery in FROM creates a virtual table that you can join, group, and query just like a physical table on disk.

Recap Coaching

Remind students of the 3 subquery slots introduced in Session 24: WHERE, SELECT, and FROM. Today we conquer the FROM slot.

💸
RetailMart Treasury: The Phantom Revenue THE DISASTROUS MULTI-CHILD JOIN FAN-OUT
FINANCIAL AUDIT EXAMPLE STORY • NAMES & NUMBERS MADE UP REAL DATA MISTAKE 🕘 QUARTER-END RECONCILIATION
STEP 01 • THE DIRECT MULTI-JOIN
junior-finance-analyst Q3 Closing
“I joined sales.orders to sales.order_items and sales.payments in one query to show total items and total collected revenue together.”
The query joined two 1-to-many child tables directly to the parent order header in a single flat FROM clause.
STEP 02 • CARTESIAN MULTIPLICATION
💥 ₹18.4 Crore Overstatement
Fan-Out Bug
An order with 4 line items and 2 split payments produced 8 rows! Payment amounts were summed 4 times, inflating reported bank collections by ₹18.4 Crore!
💥 DISTINCT Band-Aid Fails
SUM(DISTINCT) Trap
Using SUM(DISTINCT payment) wiped out genuine duplicate payments of ₹500, corrupting legitimate customer transactions.
STEP 03 • PRE-AGGREGATED DERIVED TABLES
DERIVED
🐘 Fan-Out Immune Reconciliation
SELECT o.order_id, i.gross, p.paid
FROM sales.orders o
LEFT JOIN (
  SELECT order_id, SUM(gross_amount) AS gross
  FROM sales.order_items GROUP BY order_id
) i ON o.order_id = i.order_id
LEFT JOIN (
  SELECT order_id, SUM(amount) AS paid
  FROM sales.payments GROUP BY order_id
) p ON o.order_id = p.order_id;
-- Pre-aggregating guarantees 1:1 join!
✓ Isolated Child Grains 100% Exact Numbers
STEP 04 • CORE PRINCIPLE Never join two 1-to-many child tables directly to a common parent. Always pre-aggregate each child table to the parent grain inside an independent derived table before joining.

Story Coaching

Draw the multiplication matrix on the board: 4 items × 2 payments = 8 rows. Show how each payment amount gets duplicated 4 times.

From Story → SQL: Pre-Aggregating Grain in FROM

How SQL engines parse inline derived tables and treat them as first-class relational sources.

STEP 01 • DEFINE INLINE
Enclose Query in Parentheses
(SELECT store_id, SUM(net_total)...)
The inner query executes as an independent relational block, computing aggregations prior to joining.
STEP 02 • MANDATORY ALIAS
Assign an Alias Contract
AS agg_orders
Every derived table MUST have an alias. The alias registers the virtual table in the relational namespace for outer column qualification.
STEP 03 • CLEAN 1:1 JOIN
Join at Normalized Grain
ON s.store_id = agg_orders.store_id
Because the derived table produces exactly 1 row per store, the join executes with zero risk of row multiplication.
🛡️
The Mental Model: Think of a derived table as an ephemeral spreadsheet created on the fly. You run a subquery to make the spreadsheet, give it a name, and immediately query it.

Bridging Anchor

Emphasize the mental model: A derived table is simply a query whose output behaves as a table inside another query.

Visual Studio: Derived Tables — Virtual Relations in FROM

Click execution architectures below to observe how subqueries in FROM create temporary in-memory tables.

FROM ARCHITECTURE:
RAW MULTI-TABLE JOIN • UNAGGREGATED TRANSACTION GRAIN
FROM stores s JOIN orders o → 1,50,000+ Raw Rows Sent to Hash Join
Heavy Intermediate Grain: Joining physical tables directly before aggregating forces PostgreSQL to allocate memory for 1,50,000 intermediate joined rows. Memory pressure surges and query latency degrades.
Pillar 01
Virtual Inline View
A derived table is an inline subquery in the FROM clause that acts exactly like a temporary table for the duration of the query.
Pillar 02
Mandatory Alias Contract
PostgreSQL strictly mandates an alias for every subquery in FROM: FROM (...) AS sub. Omitting it throws a syntax error!
Pillar 03
Grain Normalization
Pre-aggregating in a derived table collapses lakhs of granular transactions into one summary row per entity before joins occur.
The Derived Table Rule: Every subquery in FROM must have an alias • Acts as a temporary inline view
Tested in every entry-level and senior SQL technical assessment.

Teaching Anchor

Click Mode 2: Show how pre-aggregating 1,50,000 orders down to 200 store rows makes the final join instantaneous.

Definition: Derived Table Syntax & The Alias Contract

Embedding aggregated virtual tables in the FROM clause to decouple metric calculation from presentation.

Syntax 01
Enclosing Parentheses
The inner query is enclosed within parentheses directly in the FROM or JOIN clause, defining its operational scope.
Syntax 02
The AS agg Alias
You must assign an identifier (e.g. AS agg). Outer clauses reference inner columns via agg.total_revenue.
Syntax 03
Clean Outer Joins
The derived table presents exactly 1 row per store, guaranteeing a strict 1-to-1 join with stores.stores.
Pre-Aggregated Store Revenue Joined to Physical Outlets • stores.stores & sales.orders ▸ Run in Playground
SELECT
  s.store_id,
  s.store_name,
  s.city,
  agg.total_orders,
  ROUND(agg.total_revenue, 2) AS total_revenue,
  ROUND(agg.total_revenue / agg.total_orders, 2) AS avg_order_value
FROM stores.stores s
JOIN (
  SELECT
    store_id,
    COUNT(*) AS total_orders,
    SUM(net_total) AS total_revenue
  FROM sales.orders
  GROUP BY store_id
) AS agg ON s.store_id = agg.store_id
ORDER BY total_revenue DESC, s.store_id ASC
LIMIT 15;

Execution Check

Have students omit AS agg in playground to see PostgreSQL's famous error: subquery in FROM must have an alias.

Visual Studio: Pre-Aggregation to Defend Against Fan-Out

Click join strategies below to see how derived tables eliminate Cartesian row multiplication across child tables.

GRAIN DEFENSE:
FAN-OUT ROW MULTIPLICATION • REVENUE CORRUPTED
Order #101: 3 Items × 2 Payments = 6 Rows • SUM(amount) MULTIPLIED 3×!
The Silent Multi-Crore Bug: When an analyst joins two independent 1-to-many child tables directly, every item multiplies against every payment. Financial metrics are inflated, reporting fake revenue!
Hazard 01
Cartesian Child Cross
Child tables (items and payments) have no relationship to each other. Joining both to orders creates an accidental Cartesian product between children.
Defense 02
Pre-Aggregate in Derived Tables
Aggregate each child table to the order grain before joining: sum items by order_id, sum payments by order_id, then join to orders.
Pillar 03
Strict 1:1 Cardinality
Because both derived tables produce exactly 1 row per order_id, all joins remain strictly 1-to-1 with zero row multiplication.
The Fan-Out Defense Law: Never join two 1-to-many child tables directly • Pre-aggregate each in a derived table first
The standard architectural pattern taught in enterprise data modeling.

Teaching Anchor

Draw on the board: Order 1 has 3 items (₹100, ₹200, ₹300) and 2 payments (₹300, ₹300). Show how joining them produces 6 rows, and summing payment amount gives ₹1,800 instead of ₹600!

Definition: Fan-Out Defense Architecture

Engineering reliable financial reconciliation queries by isolating child table grains inside derived tables.

Pattern 01
Independent Aggregation
Derived table i aggregates items; derived table p aggregates payments. Neither interferes with the other.
Pattern 02
Reconciliation Accuracy
Financial audit teams can safely compare items_gross against total_amount_paid row-by-row without fear of inflated sums.
Pattern 03
LEFT JOIN Preservation
Using LEFT JOIN preserves pending orders that have not yet recorded items or completed payments.
Fan-Out Protected Order Financial Dashboard • orders, order_items & payments ▸ Run in Playground
SELECT
  o.order_id,
  o.order_date,
  COALESCE(i.item_count, 0) AS total_items,
  COALESCE(i.items_gross, 0) AS total_items_gross,
  COALESCE(p.payment_count, 0) AS total_payments,
  COALESCE(p.total_paid, 0) AS total_amount_paid
FROM sales.orders o
LEFT JOIN (
  SELECT
    order_id,
    COUNT(*) AS item_count,
    ROUND(SUM(gross_amount), 2) AS items_gross
  FROM sales.order_items
  GROUP BY order_id
) i ON o.order_id = i.order_id
LEFT JOIN (
  SELECT
    order_id,
    COUNT(*) AS payment_count,
    ROUND(SUM(amount), 2) AS total_paid
  FROM sales.payments
  GROUP BY order_id
) p ON o.order_id = p.order_id
ORDER BY o.order_id DESC
LIMIT 15;

Execution Check

Have students run this in playground: note how total_items and total_payments are accurate counts without any double counting.

Visual Studio: Sibling Derived Table Joins

Click execution modes below to observe how modular derived tables can be joined to each other as peers.

SIBLING JOIN:
SIBLING DERIVED TABLES • MODULAR DECOUPLED AGGREGATION
FROM (regional_sales) rev JOIN (regional_staff) emp ON rev.region_id = emp.region_id
Modular Metric Synthesis: Two independent derived tables compute regional revenue and regional employee headcount in parallel. They join cleanly on region_id at a unified executive grain.
Pillar 01
Peer Derived Relations
Neither derived table is nested inside the other. Both live side-by-side as peers in the FROM clause, joined on a common dimension key.
Pillar 02
Decoupled Aggregates
One query aggregates customer orders; the other aggregates store employees. Completely prevents cross-table row duplication.
Pillar 03
Executive KPI Math
Outer clauses compute complex cross-domain ratios, such as revenue / employee_count, with zero fear of cardinality distortion.

Teaching Anchor

Demonstrate how sibling derived tables allow calculating productivity metrics across two completely separate operational tables.

Definition: Sibling Derived Table Architecture

Synthesizing multiple independent operational domains at a shared regional dimension grain.

01
Decoupled Domains
Sales orders and HR staffing records are aggregated independently, avoiding messy Cartesian joins.
02
NULLIF Division Guard
Always wrap the denominator in NULLIF(emp.employee_count, 0) to prevent catastrophic division-by-zero crashes.
03
Unified Presentation
Outer SELECT presents revenue, order volume, staffing, and efficiency in a single executive summary.
Regional Revenue vs Workforce Productivity • stores, orders & employees ▸ Run in Playground
SELECT
  rev.region_id,
  rev.total_revenue,
  rev.order_count,
  emp.employee_count,
  ROUND(rev.total_revenue / NULLIF(emp.employee_count, 0), 2) AS revenue_per_employee
FROM (
  SELECT
    s2.region_id,
    ROUND(SUM(o.net_total), 2) AS total_revenue,
    COUNT(DISTINCT o.order_id) AS order_count
  FROM stores.stores s2
  JOIN sales.orders o ON s2.store_id = o.store_id
  GROUP BY s2.region_id
) rev
JOIN (
  SELECT
    s3.region_id,
    COUNT(*) AS employee_count
  FROM stores.stores s3
  JOIN stores.employees e ON s3.store_id = e.store_id
  GROUP BY s3.region_id
) emp ON rev.region_id = emp.region_id
ORDER BY rev.total_revenue DESC, rev.region_id ASC
LIMIT 15;

Query Breakdown

Point out NULLIF(emp.employee_count, 0): In SQL, division by zero halts the entire query. NULLIF turns 0 into NULL, which turns the quotient into NULL safely.

Visual Studio: Stepping Stone to CTEs — Derived Tables vs CTEs

Comparing the inline nested syntax of derived tables against top-down Common Table Expressions.

SYNTACTIC STYLE:
DERIVED TABLE STYLE • NESTED INSIDE-OUT IN FROM
SELECT ... FROM table JOIN (SELECT ... FROM child GROUP BY ...) AS derived_agg
Inside-Out Nesting: Derived tables are declared inline within the FROM or JOIN clause. They are perfect for single-use pre-aggregations, but can become deeply nested when chaining multiple transformations.
Pillar 01
Derived: Immediate Scope
Declared right where it is consumed in FROM. Can only be referenced once in that specific join tree.
Pillar 02
CTE: Reusable Scope
Declared top-down with WITH (Session 28). Can be referenced multiple times across the query.
Pillar 03
Identical Optimizer Plans
In PostgreSQL 12+, CTEs and derived tables produce identical execution plans. The difference is purely code organization.

CTE Teaser

Tell students: If they master derived tables today, CTEs in Session 28 will feel natural and effortless.

Definition: Modular Derived Tables & CTE Bridge

Structuring clean, readable queries by encapsulating aggregation logic inside derived tables.

01
Single Responsibility
The derived table computes aggregation metrics; the outer query handles joining, presentation, and filtering.
02
Predicate Pushdown
The optimizer automatically pushes outer WHERE predicates into the derived table when possible, minimizing scanned tuples.
03
Clean Maintenance
Modifying business logic in the derived query leaves outer report presentation columns completely intact.
Pre-Aggregated Brand Product Catalog • core.dim_brand & products.products ▸ Run in Playground
SELECT
  b.brand_id,
  b.brand_name,
  agg.product_count,
  ROUND(agg.avg_price, 2) AS avg_price,
  ROUND(agg.max_price, 2) AS max_price
FROM core.dim_brand b
JOIN (
  SELECT
    brand_id,
    COUNT(*) AS product_count,
    AVG(price) AS avg_price,
    MAX(price) AS max_price
  FROM products.products
  GROUP BY brand_id
) AS agg ON b.brand_id = agg.brand_id
WHERE agg.product_count >= 10
ORDER BY agg.avg_price DESC, b.brand_id ASC
LIMIT 15;

Execution Note

Demonstrate predicate pushdown: notice how the inner subquery groups products, but only qualifying brands appear in the final report.

Common Mistakes: Derived Table Pitfalls

Four frequent errors developers and data engineers encounter with derived tables in the FROM clause.

Antipattern 01
The Missing Table Alias
Forgetting to assign an identifier like AS agg after the closing parenthesis in FROM, triggering an immediate syntax error.
Antipattern 02
Uncorrelated Scope Blindness
Attempting to reference outer query columns from inside a standard derived table without using the LATERAL keyword.
Antipattern 03
Direct Child Join Fan-Out
Joining multiple 1-to-many child tables directly to a parent without pre-aggregating, corrupting financial sums via row multiplication.
Antipattern 04
Division by Zero in Ratios
Calculating ratios like revenue / employee_count without NULLIF(col, 0), causing runtime crashes on zero-staff regions.
Production Danger: Antipattern 03 (Direct Child Join Fan-Out) is the #1 cause of audit failures in enterprise business intelligence.
Next: Enter the Practice Arena Gateway to solve real-world derived table challenges.

Warning Anchor

Emphasize Antipattern 01 (missing alias) and Antipattern 03 (fan-out). Both appear frequently in senior technical interviews.

▶ Enter Practice Arena

Practice Arena: Derived Tables in Practice

Work through 4 graded challenges below. Test your queries live in the interactive terminal.

Arena Complete: Every solution is 100% verified on PostgreSQL 18 against RetailMart's live catalog.
Proceed to the Interview Masterclass to master high-frequency technical questions.

Live Arena Execution

Give students 10 minutes to complete the drills. Focus on Challenge 3 (fan-out defense) and Challenge 4 (sibling derived tables).

Interview Masterclass: Derived Tables & Virtual Relations

Authentic technical questions asked by senior engineering and data analytics interview panels.

01 • Mandatory Table Alias
02 • Join Fan-Out Defense
03 • Outer Scope References
04 • Derived vs CTE vs View
05 • Optimizer Materialization
06 • Column Collisions
07 • Pre-Aggregation Perf
08 • Sibling Derived Pattern
RELATIONAL SYNTAX
“Why is a table alias mandatory for every derived table in PostgreSQL?”
In relational SQL grammar, every relation referenced in the FROM clause must have an identifiable name in the relational catalog namespace. When you write an inline subquery, PostgreSQL generates a temporary anonymous relation. Without an explicit alias (e.g. AS agg), outer clauses (SELECT, JOIN, WHERE) have no identifier to qualify and resolve column references.
Interview Trap: Omitting AS alias_name after a closing parenthesis in FROM. PostgreSQL halts immediately with error: 'subquery in FROM must have an alias'.

Interview Coaching

Have students practice explaining Question 2 (Join Fan-Out Defense). It is a classic senior interview question for analytics engineers.

Self-Check: 10 Master Flashcards

Click cards to test your retention of derived table syntax, fan-out elimination, and multi-grain joins.

Why is an alias mandatory for derived tables in the FROM clause?
Relational Namespace! In SQL grammar, every relation in FROM must have an identifier to resolve column references.
What is join fan-out?
Cartesian explosion! Joining two 1-to-many child tables directly multiplies row counts and inflates aggregate sums.
How does pre-aggregating in a derived table prevent fan-out?
Grain Normalization! Collapsing child rows into one summary row per parent ensures a strict 1:1 join.
Why is SUM(DISTINCT amount) an invalid fix for fan-out?
Deduplication Bug! It destroys legitimate identical payments (e.g. two separate ₹500 transactions).
Can a standard derived table reference columns from the outer query?
NO! Standard derived tables evaluate independently. You must use a LATERAL join to reference outer columns.
What is the difference between a derived table and a CTE?
Readability and scope! Derived tables are nested inside-out; CTEs are declared top-down with WITH and are reusable.
Does PostgreSQL always materialize derived tables on disk?
NO! The optimizer flattens simple derived tables into join trees or pushes WHERE predicates down via Predicate Pushdown.
What is a sibling derived table pattern?
Peer Join! Joining two independent derived tables on a common dimension key in the FROM clause.
Why wrap denominators in NULLIF(col, 0) in ratio calculations?
Crash Prevention! Division by zero causes a fatal error; NULLIF converts 0 to NULL, yielding safe NULL output.
What happens if you omit column aliases inside a derived table?
Ambiguity or ugly names! Outer queries cannot reference raw aggregate expressions like COUNT(*) without an alias.

Self-Check Review

Review card 2 (join fan-out) and card 5 (outer correlation limit). Both are essential for writing production queries.

Key Takeaways: The 6 Laws of Derived Table Architecture

Master these six rules to structure modular, fan-out immune queries in PostgreSQL.

01
The Alias Mandate
Every subquery in the FROM clause must have an assigned alias: FROM (...) AS alias_name. Never omit it.
02
Fan-Out Immunity
Never join two 1-to-many child tables directly to a common parent. Always pre-aggregate each child in an independent derived table first.
03
Grain Normalization
Pre-aggregating collapses lakhs of transactions into clean summary rows before joining, delivering blazingly fast execution.
04
Sibling Synthesis
Join multiple derived tables side-by-side as peers in FROM to combine disparate operational metrics at a shared dimension grain.
05
NULLIF Division Shield
Always wrap ratio denominators in NULLIF(denominator, 0) to guard against fatal division-by-zero database crashes.
06
CTE Precursor
Derived tables are the foundation of Common Table Expressions (CTEs). Master inline nesting today for effortless CTE fluency in Session 28.

Takeaways Summary

Have students snapshot this slide: it is the comprehensive mental cheat sheet for derived tables and grain defense.

Quick Reference: Derived Table Syntax & Architecture

A syntax reference card for virtual tables, pre-aggregation patterns, and fan-out defense.

Master Derived Table Reference Query ▸ Run in Playground
SELECT
  s.store_id,
  s.store_name,
  s.city,
  agg.order_count,
  ROUND(agg.total_revenue, 2) AS total_revenue
FROM stores.stores s
JOIN (
  SELECT
    store_id,
    COUNT(*) AS order_count,
    SUM(net_total) AS total_revenue
  FROM sales.orders
  GROUP BY store_id
) AS agg ON s.store_id = agg.store_id
ORDER BY total_revenue DESC, s.store_id ASC
LIMIT 10;
FROM Slot
Virtual View
FROM (SELECT ... GROUP BY ...) AS agg
Subquery output acts as an inline table relation.
JOIN Slot
Pre-Aggregated Join
JOIN (SELECT ... ) AS agg ON key = agg.key
Guarantees strict 1:1 join cardinality.
Fan-Out Defense
Multi-Child Join
orders o LEFT JOIN (items) i LEFT JOIN (payments) p
Pre-aggregates children to avoid row explosion.
Sibling Join
Peer Relations
FROM (subquery1) s1 JOIN (subquery2) s2 ON key
Combines disparate metric domains at shared grain.
Safe Ratios
NULLIF Guard
numerator / NULLIF(denominator, 0)
Eliminates fatal division-by-zero exceptions.
Predicate Pushdown
Optimizer Feature
PostgreSQL pushes outer WHERE conditions into the derived subquery automatically.

Reference Usage

Bookmark this quick reference for practical syntax lookup during live coding and homework challenges.

Take-Home Challenge: Enterprise Derived Table Synthesis

Solidify your derived table mastery with these 4 production challenges across RetailMart schemas.

CHALLENGE 01 • OPERATIONS

Pre-Aggregated Store Revenue

Pre-aggregate order counts and total sales in a derived table in FROM, then join to stores.stores to report store revenue and average order value.

Starter Template ▸ Run in Playground
SELECT
  s.store_id,
  s.store_name,
  s.city,
  agg.total_orders,
  ROUND(agg.total_revenue, 2) AS total_revenue
FROM stores.stores s
JOIN (
  SELECT
    store_id,
    COUNT(*) AS total_orders,
    SUM(net_total) AS total_revenue
  FROM sales.orders
  GROUP BY store_id
) AS agg ON s.store_id = agg.store_id
ORDER BY total_revenue DESC, s.store_id ASC
LIMIT 10;
CHALLENGE 02 • MERCHANDISING

Brand Catalog Summary

Use a derived table to pre-aggregate product metrics by brand_id, then join to core.dim_brand to report catalog depth and average pricing.

Starter Template ▸ Run in Playground
SELECT
  b.brand_id,
  b.brand_name,
  agg.product_count,
  ROUND(agg.avg_price, 2) AS avg_price
FROM core.dim_brand b
JOIN (
  SELECT
    brand_id,
    COUNT(*) AS product_count,
    AVG(price) AS avg_price
  FROM products.products
  GROUP BY brand_id
) AS agg ON b.brand_id = agg.brand_id
WHERE agg.product_count >= 10
ORDER BY agg.avg_price DESC, b.brand_id ASC
LIMIT 10;
CHALLENGE 03 • TREASURY

Fan-Out Immune Reconciliation

Pre-aggregate order_items and payments in separate derived tables to compare items gross vs collected payments per order without multiplication.

Tables: orders, order_items, payments • Grain: 1:1 order grain • Pattern: Dual LEFT JOIN
CHALLENGE 04 • PRODUCTIVITY

Regional Revenue per Employee

Join sibling derived tables on region_id to compare total sales against total employee headcount with NULLIF division protection.

Tables: stores, orders, employees • Metric: revenue / NULLIF(employees, 0)

Homework Guidance

Assign these 4 challenges for student practice before the next live session on Correlated Subqueries & EXISTS.

Your SQL Journey: Module 3 Advanced Analytics!

You have mastered single-table queries, relational joins, set theory, and foundational derived tables. Here is your roadmap forward.

✓ SESSION 01 • FOUNDATIONS
What is SQL? & Relational Architecture
Client-server architecture, relational engines, tables, rows, columns, and data types.
✓ SESSION 17 • RELATIONAL JOINS
INNER, LEFT & RIGHT JOINs
Combining relations horizontally with key predicates, cardinality matching, and NULL preservation.
• SESSION 25 • YOU ARE HERE
Subqueries II: Derived Tables in FROM
Pre-aggregating transactional grains, defending against fan-out, and multi-source virtual relations.

Milestone Celebration

Celebrate with the class: they have mastered derived tables and are now ready for correlated row-by-row execution in the next class.

Coming Next: Session 26 • Correlated Subqueries & EXISTS

Moving beyond independent subqueries: executing inner queries dynamically for every outer row.

SESSION 26 PREVIEW
Correlated Subqueries
How do you find products cheaper than their own category's average? Inner queries that reference the outer row dynamically!
SESSION 26 PREVIEW
The EXISTS Operator
Learn why EXISTS is the king of semi-joins: short-circuiting execution the instant a single matching record is confirmed.
SESSION 27 PREVIEW
LATERAL Joins
Execute subqueries inside the FROM clause with access to outer columns — unlocking top-N products per category in one query!
Correlated Subqueries & EXISTS on Live Schedule → Review From Beginning ↺

Closing Remarks

Send students off with excitement for Correlated Subqueries and EXISTS in Session 26.

→ next   ← back   F fullscreen   H hide bars   N notes
1 / 41