Module 3 › Session 24 · Subqueries I: Scalar & Multi-Row (IN, ANY, ALL)

Subqueries I: Scalar & Multi-Row (IN, ANY, ALL)

Master dynamic single-cell scalar expressions, dynamic key set membership with IN, universal and existential quantifiers (ALL, ANY), and guard against the 3VL NOT IN trap.

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 24 • TOPIC 28

Subqueries I: Scalar & Multi-Row

Dynamic Aggregate Thresholds, Quantified Set Membership (IN, ANY, ALL) & Execution Plans
23
Interactive Scenes
4
Visual Studios
4
Arena Challenges
8
Interview Scenarios
Core Focus: Atomic 1×1 Shapes, Dynamic WHERE Thresholds, The 3VL NOT IN Guard & InitPlan Caching
✓ Verified on PostgreSQL 18

Welcome to Session 24

Today we kick off Module 3: Advanced Analytical SQL. We transition from static hardcoded filters to dynamic nested subqueries.

Today's Agenda — The Nested Subquery Architecture

A structured four-pillar journey from atomic single-cell scalar expressions to multi-row membership and optimization.

PILLAR 01
🔍 Scalar Subqueries
01Atomic 1-Row Resolution
02Dynamic WHERE Thresholds
03SELECT Benchmark Columns
PILLAR 02
🔗 Multi-Row & IN
04Dynamic Key Sets with IN
05The Fatal NOT IN NULL Trap
06Preserving Entity Grain
PILLAR 03
⚖️ Set Comparisons
07Universal Matches with ALL
08Existential Matches with ANY
09Cardinality Crash Prevention
PILLAR 04
🎯 Practice & Next
10SubPlan vs InitPlan Optimizer
11Practice Arena: 4 Challenges
12Next: Derived Tables in FROM
💡
Why this matters: Real retail datasets evolve continuously. Hardcoded filters like WHERE spend > 50000 rot the moment business conditions shift. Subqueries make analytical thresholds self-calibrating.

Teaching Note

Emphasize the shift from Module 2 (combining relations horizontally/vertically) to Module 3 (dynamic self-referential nested evaluation).

Where We Left Off — The Relational Foundation

In Session 23, we mastered vertical concatenation and set difference. Today we introduce dynamic nested evaluation.

📦 SESSION 23 • COMPLETED

What Set Operations Solved

-- Session 23: Stack streams or isolate churn with EXCEPT
SELECT cust_id FROM sales.orders WHERE order_date >= '2024-01-01'
EXCEPT
SELECT cust_id FROM sales.orders WHERE order_date >= '2026-01-01';
Last class, we mastered combining independent result sets vertically with UNION and discovering discrepancies with EXCEPT. We reconciled order streams and customer cohorts across time.
✓ Set algebra harmonizes multiple queries into unified streams
⚠️ SESSION 24 • THE MISSION

Why Hardcoded Constants Break Down

-- The fragile static filter:
SELECT order_id, net_total FROM sales.orders
WHERE net_total > 50000.00;
⚠️ Why 50,000? If average basket size shifts, the filter rots!
Static constants require analysts to run Query 1, calculate the average by hand, and copy-paste it into Query 2. Subqueries eliminate this manual friction by nesting the benchmark dynamically.
🔍 Today: Dynamic thresholds that compute in a single transaction pass
🛡️
The Core Distinction: Set operations combine multiple queries side-by-side or stacked. Subqueries nest one query inside another to provide dynamic values for filtering and projection.

Recap Coaching

Connect Session 23 to Session 24: both deal with multi-query architecture, but subqueries feed results into outer query expressions.

🛒
RetailMart Operations: Diwali Rush THE PERIL OF THE HARDCODED FILTER CONSTANT
PRODUCTION AUDIT EXAMPLE STORY • NAMES & NUMBERS MADE UP REAL RETAIL SCENARIO 🕘 09:30 AM PEAK LOGISTICS
STEP 01 • THE HARDCODED THRESHOLD
lead-data-analyst Diwali Morning
“I set the VIP order filter to WHERE net_total > 50000. That was the average order value when I built the dashboard back in July.”
During the holiday festival surge, high-ticket electronics purchases push the real daily average order spend to ₹82,162.04.
STEP 02 • REPORTING FAILURE
💥 45,000 False Alerts
Stale Constant
Over 45,000 orders trigger VIP fulfillment alerts. The executive alert queue crashes because ₹50,000 is no longer an exceptional basket size.
💥 Manual Copy-Paste Lag
Two-Query Hassle
The operations team frantically runs SELECT AVG(...), calculates today's new number, and manually edits SQL scripts every 2 hours.
STEP 03 • SELF-CALIBRATING QUERY
SUBQUERY
🐘 Dynamic VIP Threshold
SELECT order_id, cust_id, net_total
FROM sales.orders
WHERE net_total > (
  SELECT AVG(net_total)
  FROM sales.orders
)
ORDER BY net_total DESC
LIMIT 10;
-- Evaluates dynamic average automatically
✓ 1 Atomic Subquery Zero Maintenance
STEP 04 • CORE PRINCIPLE Never hardcode what the database engine can compute dynamically. A subquery transforms brittle, hardcoded thresholds into self-adapting, resilient analytical pipelines.

Story Anchor

Use the Diwali rush story: thresholds must adapt to real-time sales velocity, not static human assumptions from six months ago.

From Story → SQL: The Three Subquery Slots

Where can you nest a subquery in an ANSI SQL statement? Anywhere an expression or relation is expected.

SLOT 01 • WHERE
Dynamic Filter Threshold
WHERE net_total > (SELECT AVG(net_total)...)
The subquery resolves to an atomic scalar constant or a set of keys, filtering rows before they reach aggregation.
SLOT 02 • SELECT
Benchmark Column Projection
SELECT order_id, (SELECT AVG(net_total)...) AS avg_bench
Projects enterprise-level aggregate metrics as companion columns alongside individual transaction details.
SLOT 03 • HAVING
Group Benchmark Filter
HAVING SUM(sales) > (SELECT AVG(store_rev)...)
Filters grouped store or brand buckets against dynamically computed national retail averages.
🛡️
The Syntax Rule: Subqueries must ALWAYS be enclosed in round parentheses (...). The parser requires parentheses to distinguish nested query blocks from outer query syntax.

Bridging Anchor

Emphasize: wherever you can write a scalar literal (like 50000 or 'Delhi'), you can write a parenthesized subquery that evaluates to that type.

Visual Studio: Scalar Subquery Execution Engine

Click execution modes below to contrast valid atomic 1-row evaluation against fatal multi-row cardinality crashes.

EVALUATION MODE:
ATOMIC SCALAR IN WHERE • DYNAMIC THRESHOLD
WHERE net_total > (SELECT AVG(net_total) FROM orders) → WHERE net_total > ₹82,162.04
Dynamic Predicate: The inner aggregate evaluates first to a single scalar constant (₹82,162.04). The outer query then filters transactions against today's real store average without manual hardcoding.
Pillar 01
Strict 1 × 1 Shape
A scalar subquery must produce exactly 1 row and 1 column. It evaluates to an atomic literal value that replaces the subquery block.
Pillar 02
InitPlan Caching
When uncorrelated, PostgreSQL runs the inner query once prior to table scanning, storing the scalar result in an in-memory InitPlan register.
Pillar 03
Cardinality Contract
If the inner query returns 2 or more rows in a scalar context, the query halts instantly with error: more than one row returned.

Visual Demonstration

Click Mode 3: Show students the exact error message PostgreSQL produces when a subquery returns multiple rows where one was expected.

Definition: Scalar Subqueries in Practice

The formal relational semantics and execution rules of single-cell scalar subquery expressions.

01
WHERE Slot
Substitutes for an atomic comparison literal. Evaluates to a single value compared using =, >, <, >=, or <=.
02
SELECT Slot
Adds a global scalar calculation to every output row. Enables relative deviation math like price - (SELECT AVG(price)...).
03
Zero Rows = NULL
If an inner query matches zero rows, it evaluates to NULL (not an error). Comparisons against NULL yield UNKNOWN.
Scalar Subquery Execution • sales.orders (1,50,000 Rows) ▸ Run in Playground
SELECT
  order_id,
  order_date,
  cust_id,
  ROUND(net_total, 2) AS net_total,
  (SELECT ROUND(AVG(net_total), 2) FROM sales.orders) AS global_avg_ticket
FROM sales.orders
WHERE net_total > (
  SELECT AVG(net_total)
  FROM sales.orders
)
ORDER BY net_total DESC, order_id ASC
LIMIT 10;

Execution Breakdown

Walk through the query: First, the subquery computes the global average (₹82,162.04). Then, the outer query sieves only orders exceeding that value.

Visual Studio: Multi-Row Set Membership (IN & NOT IN)

Click membership modes below to see how dynamic key sets work and why an unhandled NULL causes silent catastrophic failure.

MEMBERSHIP OPERATOR:
DYNAMIC SET MEMBERSHIP • IN (SUBQUERY)
store_id IN (1, 4, 9, 155) → Matches orders placed at verified flagship branches
Set Membership: Evaluates whether the outer column matches any element in the dynamic inner list. Preserves parent row grain without creating duplicate rows like an INNER JOIN.
Pillar 01
1 Column, N Rows
Multi-row subqueries project exactly 1 column and any number of rows. They evaluate to a mathematical set of scalar values.
Pillar 02
Grain Preservation
Using WHERE id IN (subquery) tests existence without duplicating rows, completely avoiding the need for an expensive DISTINCT.
Pillar 03
The 3VL NULL Law
If the inner set contains even one NULL, NOT IN evaluates to UNKNOWN for every row, wiping out the entire result set!

Trap Demonstration

Demonstrate Mode 3: The 3VL NULL trap is responsible for 80% of silent SQL production bugs in senior data engineering.

Definition: Multi-Row Subqueries & Safe NOT IN

The mechanics of dynamic set membership and the mandatory IS NOT NULL guard.

01
IN Dynamic Sets
Feeds a dynamic column of keys to the outer filter. Evaluates to TRUE if outer_val = inner_val_1 OR outer_val = inner_val_2....
02
The NOT IN Rule
Expands with AND logic: outer_val != inner_val_1 AND outer_val != inner_val_2.... A NULL makes the entire conjunction UNKNOWN!
03
The Mandatory Guard
Always include WHERE key IS NOT NULL inside every NOT IN subquery to guarantee reliable exclusion behavior.
Dynamic Multi-Row Filter • sales.orders & stores.stores ▸ Run in Playground
SELECT
  order_id,
  order_date,
  store_id,
  ROUND(net_total, 2) AS net_total
FROM sales.orders
WHERE store_id IN (
  SELECT store_id
  FROM stores.stores
  WHERE city IN ('Delhi', 'Bengaluru')
    AND store_id IS NOT NULL
)
ORDER BY order_date DESC, order_id ASC
LIMIT 10;

Safe NOT IN Law

Drill this into students' minds: Whenever you type NOT IN, immediately type WHERE column IS NOT NULL in the inner query.

Visual Studio: ANY and ALL Quantified Operators

Quantified comparison operators that compare an outer scalar against an entire multi-row subquery list.

QUANTIFIED OPERATOR:
> ALL • EXCEEDS THE ENTIRE SET (EXCEEDS MAX)
price > ALL (Brand 60 Prices: ₹51 to ₹1,694.72) ≡ price > ₹1,694.72
Universal Assertion: The condition holds TRUE only if the candidate value is strictly greater than EVERY single value returned by the subquery. Equivalent to testing against the set's maximum.
Pillar 01
> ALL ≡ > MAX
Must be greater than every value in the subquery. If the candidate value exceeds the maximum of the set, the condition passes.
Pillar 02
> ANY ≡ > MIN
Must be greater than at least one value in the subquery. If the candidate value exceeds the minimum of the set, the condition passes.
Pillar 03
= ANY ≡ IN
val = ANY (list) is ANSI standard SQL syntax identical to val IN (list). PostgreSQL treats them as exact synonyms.

Teaching Anchor

Highlight the mental shortcut: `> ALL` means greater than the highest; `> ANY` means greater than the lowest.

Definition: Quantified Comparisons (ANY & ALL)

How SQL evaluates universal (> ALL) and existential (> ANY) expressions against subquery results.

01
Universal Contract
> ALL requires every comparison to be true. If the subquery is empty, it returns TRUE (vacuous truth).
02
Existential Contract
> ANY requires only one comparison to be true. If the subquery is empty, it returns FALSE.
03
NULL Handling
Like IN, any NULL inside the subquery list can cause ALL comparisons to evaluate to UNKNOWN. Always add IS NOT NULL.
Products Priced Above Every Brand 60 Item • products.products ▸ Run in Playground
SELECT
  product_id,
  product_name,
  brand_id,
  ROUND(price, 2) AS price
FROM products.products
WHERE price > ALL (
  SELECT price
  FROM products.products
  WHERE brand_id = 60
    AND price IS NOT NULL
)
ORDER BY price ASC, product_id ASC
LIMIT 10;

Query Walkthrough

Brand 60 has items topping out at ₹1,694.72. The query finds products priced above this maximum threshold across all other brands.

Visual Studio: Optimizer Execution (InitPlan vs SubPlan)

Understanding how the PostgreSQL cost-based optimizer executes subqueries under the hood.

EXECUTION ENGINE:
INITPLAN • RUNS ONCE AT STARTUP • RESULT CACHED
InitPlan 1 (returns $0) → Subquery runs 1 time → ₹82,162.04 cached in register
Startup Evaluation: An uncorrelated scalar subquery has zero dependencies on outer rows. PostgreSQL runs it once at execution start, caches the result in an in-memory register, and substitutes the scalar literal throughout the query.
Pillar 01
InitPlan: Run Once
Uncorrelated subqueries evaluate at query startup. Zero per-row scan penalty; result acts as an in-memory constant.
Pillar 02
Hashed SubPlan
IN lists build a RAM hash table. Membership check takes O(1) time per outer candidate row.
Pillar 03
SubPlan: Row Loop
Correlated subqueries loop per outer row. Indexing join keys is mandatory to avoid catastrophic full scans.
⚡
The Performance Rule: Uncorrelated subqueries execute in milliseconds because they run only once. Correlated subqueries require indexes on join keys to prevent nested table scans.

Optimizer Pacing

Explain why uncorrelated subqueries are so fast: PostgreSQL doesn't re-run them for every row; it caches them as InitPlans.

Definition: Subquery Flattening & Semi-Joins

How PostgreSQL rewrites declarative IN subqueries into high-speed semi-join relational operations.

01
Subquery Pull-Up
The planner pulls simple subqueries up into the parent query, converting WHERE id IN (...) into an optimized Semi-Join tree.
02
Early Short-Circuit
As soon as the inner query confirms a match for an outer key, the semi-join short-circuits evaluation without reading remaining child rows.
03
Zero Fan-Out
Unlike an INNER JOIN that multiplies parent rows for each child match, a semi-join guarantees strictly 1 output row per qualifying parent.
Optimized Semi-Join IN Query • stores.stores & sales.orders ▸ Run in Playground
SELECT
  s.store_id,
  s.store_name,
  s.city
FROM stores.stores s
WHERE s.store_id IN (
  SELECT o.store_id
  FROM sales.orders o
  WHERE o.order_date >= '2026-01-01'
    AND o.net_total > 50000
    AND o.store_id IS NOT NULL
)
ORDER BY s.store_id ASC
LIMIT 10;

Execution Note

Demonstrate how this query returns each store exactly once, even though each store has hundreds of qualifying orders in 2026.

Common Mistakes: Subquery Antipatterns

Four costly mistakes developers and data analysts make with scalar and multi-row subqueries.

Antipattern 01
The Cardinality Explosion
Using comparison operators (=, >) with an inner query that unexpectedly returns multiple rows. Guarantees fatal crash at runtime.
Antipattern 02
The 3VL NOT IN Trap
Executing NOT IN against an inner query containing a NULL column. Evaluates to UNKNOWN and silently wipes out all candidate rows.
Antipattern 03
JOIN Duplication Overkill
Using INNER JOIN ... SELECT DISTINCT just to filter existence, creating lakhs of duplicate rows in memory before deduplication.
Antipattern 04
Unindexed Correlation
Correlating a subquery on an unindexed large table (e.g. 1.5 lakh orders), causing an expensive sequential scan for every single outer tuple.
Production Danger: Antipattern 02 (The NOT IN NULL trap) is silent: no crash, no warning, pure empty output. Always guard with IS NOT NULL!
Next: Enter the Practice Arena Gateway to solve real-world scalar and multi-row challenges.

Warning Anchor

Emphasize Antipattern 02: Remind students that an error you can see is a gift; a query that runs with zero output is a nightmare.

▶ Enter Practice Arena

Practice Arena: Subqueries 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 1 (scalar WHERE) and Challenge 3 (HAVING subquery).

Interview Masterclass: Subqueries & Scalar Expressions

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

01 • Scalar vs Multi-Row
02 • The NOT IN NULL Trap
03 • ANY vs ALL Quantifiers
04 • InitPlan vs SubPlan
05 • IN vs INNER JOIN
06 • Empty Result Evaluation
07 • Subqueries in HAVING
08 • Subquery Pull-Up
ARCHITECTURAL CONCEPTS
“What is the fundamental difference between a scalar subquery and a multi-row subquery?”
A Scalar Subquery returns strictly 1 row and 1 column (a single atomic cell). It can be used anywhere an expression or literal constant is valid (in SELECT, WHERE, HAVING).

A Multi-Row Subquery returns multiple rows of a single column. It cannot be used with comparison operators like = or >; it must be paired with quantified set membership operators such as IN, NOT IN, ANY, or ALL.
Interview Trap: Writing WHERE price > (SELECT price FROM products). As soon as the inner query returns 2 rows, PostgreSQL throws an immediate runtime exception: 'more than one row returned by a subquery used as an expression'.

Interview Coaching

Have students practice explaining Question 2 (The NOT IN NULL Trap). It is the single most tested SQL corner case in senior technical interviews.

Self-Check: 10 Master Flashcards

Click cards to test your retention of scalar shapes, set membership traps, and quantified comparison operators.

What happens if a scalar subquery returns 2 rows at runtime?
Fatal crash! PostgreSQL halts execution with: more than one row returned by a subquery used as an expression.
Why does NOT IN return 0 rows when the inner subquery has a NULL?
3VL UNKNOWN collapse! x != NULL evaluates to UNKNOWN. TRUE AND UNKNOWN evaluates to UNKNOWN, wiping out every row.
What happens if a scalar subquery matches zero rows?
Evaluates to NULL! It does NOT crash; it simply returns NULL, which causes outer equality comparisons to evaluate to UNKNOWN.
How does an uncorrelated scalar subquery execute in PostgreSQL?
Evaluated ONCE as an InitPlan! It runs prior to the outer query, caches the scalar constant, and incurs zero per-row penalty.
Why use an IN subquery instead of an INNER JOIN for filtering?
Preserves entity grain! IN checks for existence without row multiplication, avoiding the need for an expensive SELECT DISTINCT.
What is the exact equivalent of = ANY (subquery)?
The IN operator! val = ANY (subquery) is the ANSI SQL formal relational definition of val IN (subquery).
What does > ALL (subquery) mathematically evaluate to?
Greater than the maximum! val > ALL (subquery) evaluates to TRUE if val is strictly greater than MAX(subquery).
What does > ANY (subquery) mathematically evaluate to?
Greater than the minimum! val > ANY (subquery) evaluates to TRUE if val is strictly greater than MIN(subquery).
What does > ALL evaluate to if the inner subquery is empty?
Evaluates to TRUE! In relational logic, universal quantification over an empty set is vacuously TRUE for all rows.
What is the mandatory guard for every NOT IN subquery?
Always add WHERE column IS NOT NULL in the inner subquery to prevent 3VL NULL poisoning from collapsing the result set.

Self-Check Review

Review card 2 (NOT IN NULL trap) and card 4 (InitPlan). Both are mandatory knowledge for writing production SQL.

Key Takeaways: The 6 Laws of Subquery Architecture

Master these six rules to ensure robust, high-performance subquery execution in PostgreSQL.

01
Atomic Scalar Law
A scalar subquery must return strictly 1 row and 1 column. Enclose in parentheses and use aggregate functions like AVG or SUM to guarantee scalar output.
02
The 3VL NULL Shield
Never write NOT IN (subquery) without adding WHERE col IS NOT NULL inside. A single NULL collapses the entire expression to UNKNOWN.
03
Quantified Duality
> ALL requires exceeding the maximum of the inner set. > ANY requires exceeding the minimum. = ANY is identical to IN.
04
InitPlan Efficiency
Uncorrelated subqueries are evaluated once prior to table scanning and cached in memory. They impose zero per-row execution penalty on the outer query.
05
Grain Preservation
Use IN (subquery) instead of an INNER JOIN when checking for the existence of related child records to eliminate fan-out row duplication.
06
Empty Scalar Returns NULL
When an inner scalar subquery matches zero rows, it evaluates to NULL without crashing. Use COALESCE to supply safe default fallbacks.

Takeaways Summary

Have students snapshot this slide: it is the comprehensive mental cheat sheet for all subquery operations.

Quick Reference: Subquery Syntax & Semantics

A syntax reference card for scalar expressions, multi-row membership, and quantified comparisons.

Master Subquery Reference Query ▸ Run in Playground
SELECT
  order_id,
  order_date,
  cust_id,
  ROUND(net_total, 2) AS net_total,
  (SELECT ROUND(AVG(net_total), 2) FROM sales.orders) AS benchmark
FROM sales.orders
WHERE net_total > (
  SELECT AVG(net_total)
  FROM sales.orders
)
ORDER BY net_total DESC, order_id ASC
LIMIT 10;
WHERE Slot
Scalar Predicate
WHERE col > (SELECT AVG(col)...)
Filters outer rows dynamically against an aggregate benchmark.
SELECT Slot
Benchmark Column
SELECT (SELECT AVG(x)...) AS bench
Attaches overall aggregate constant to individual row details.
IN Dynamic
Set Membership
WHERE id IN (SELECT id WHERE...)
Semi-join filter that eliminates row multiplication.
Safe NOT IN
IS NOT NULL Guard
WHERE id NOT IN (SELECT id WHERE id IS NOT NULL)
Prevents 3VL UNKNOWN result collapse.
> ALL Slot
Universal Maximum
WHERE val > ALL (SELECT col...)
Asserts value is strictly higher than every inner item.
> ANY Slot
Existential Minimum
WHERE val > ANY (SELECT col...)
Asserts value is strictly higher than at least one inner item.

Reference Usage

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

Take-Home Challenge: Enterprise Subquery Synthesis

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

CHALLENGE 01 • FINANCE

Above-Average Order Filter

Write a scalar subquery in the WHERE clause to filter orders whose net_total exceeds the national average order value.

Starter Template ▸ Run in Playground
SELECT
  order_id,
  order_date,
  cust_id,
  ROUND(net_total, 2) AS net_total
FROM sales.orders
WHERE net_total > (
  SELECT AVG(net_total)
  FROM sales.orders
)
ORDER BY net_total DESC, order_id ASC
LIMIT 10;
CHALLENGE 02 • BRAND FILTERING

Premium Brand Product Filter

Use an IN subquery to identify all products belonging to flagship brands (Samsung, Apple, Sony) without duplicating rows.

Starter Template ▸ Run in Playground
SELECT
  product_id,
  product_name,
  brand_id,
  ROUND(price, 2) AS price
FROM products.products
WHERE brand_id IN (
  SELECT b.brand_id
  FROM core.dim_brand b
  WHERE b.brand_name IN ('Samsung', 'Apple', 'Sony')
)
ORDER BY price DESC, product_id ASC
LIMIT 10;
CHALLENGE 03 • BENCHMARKING

Employee Salary vs Regional Average

Project each employee's name and salary alongside the global average salary using a scalar subquery in the SELECT clause.

Table: stores.employees • Slot: SELECT (scalar) • Math: salary - avg_salary
CHALLENGE 04 • QUANTIFIED SETS

Products Exceeding Category Maximum

Use the > ALL quantified comparison operator to find products priced strictly above all items in a target budget brand.

Table: products.products • Operator: > ALL • Guard: price IS NOT NULL

Homework Guidance

Assign these 4 challenges for student practice before the next live session on Derived Tables.

Your SQL Journey: Module 3 Advanced Analytics!

You have mastered single-table queries, relational joins, set theory, and foundational subqueries. 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 24 • YOU ARE HERE
Subqueries I: Scalar & Multi-Row (IN, ANY, ALL)
Atomic 1-row evaluation, dynamic WHERE thresholds, safe NOT IN guards, and InitPlan caching.

Milestone Celebration

Celebrate with the class: they have mastered foundational subqueries and are now ready for derived tables in Session 25.

Coming Next: Session 25 • Derived Tables in FROM

Moving to the FROM clause: creating on-the-fly virtual tables and eliminating join fan-out multiplication.

SLOT 03 • FROM
The Virtual Table
Instead of querying a physical table from disk, query the output of another query: FROM (SELECT ...) AS derived.
GRAIN DEFENSE
Pre-Aggregation
Learn why joining order line items directly duplicates customer balances, and how pre-aggregating in FROM cures fan-out forever.
CTE PREVIEW
Stepping Stone to CTEs
Mastering derived tables in FROM prepares you for Session 28, where Common Table Expressions (WITH) organize virtual tables cleanly.
Derived Tables on Live Schedule → Review From Beginning ↺

Closing Remarks

Send students off with excitement for Derived Tables in the FROM clause in Session 25.

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