Module 3 › Session 26 · Correlated Subqueries & EXISTS

Correlated Subqueries & EXISTS

Master row-by-row outer query correlation, short-circuit boolean EXISTS tests, NULL-safe NOT EXISTS anti-joins, and eliminate 3VL traps.

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

← All NukteSELECT * FROM TheShiraverse

Correlated Subqueries & EXISTS

Dynamic row-by-row outer variable binding, boolean short-circuit semi-joins, and NULL-safe anti-joins in PostgreSQL 18.

23
SCENES
1
PRACTICE ARENA
4
LIVE DRILLS
8
INTERVIEW Qs

Session Orientation

Welcome to Session 26. In Session 24 and 25, we covered independent subqueries and derived tables. Today we connect inner subqueries directly to outer row tuples.

Today's Agenda — The Correlated Execution Blueprint

A four-pillar architectural progression from outer scope binding to boolean short-circuiting and optimizer plans.

PILLAR 01
🔄 Outer Scope Binding
01Outer Table Alias Binding
02Per-Row Inner Re-Execution
03SubPlan vs InitPlan Architecture
PILLAR 02
⚖️ Relative Benchmarks
04Department & Brand Baselines
05Correlated WHERE Filters
06Dynamic SELECT Columns
PILLAR 03
👁 EXISTS Semi-Joins
07Boolean Existence Testing
08Short-Circuit Execution Stop
09SELECT 1 vs SELECT * Myth
PILLAR 04
🛡️ Anti-Join Mastery
10NOT EXISTS NULL Safety
11Defeating 3VL NOT IN Traps
12Hash Anti-Join Optimization
💡
Why this matters: Real enterprise metrics are almost never evaluated against static global averages. Employees compete within their department; products compete within their brand. Correlated subqueries allow you to compute contextual, relative baselines per entity in a single query.

Teaching Note

Contrast static uncorrelated subqueries (Session 24) with dynamic correlated subqueries (Session 26). Explain variable scope in programming languages as an analogy.

Where We Left Off — From Derived Tables to Correlated Scopes

In Session 25, we mastered inline derived tables in FROM. Today we bind subqueries dynamically to outer row tuples.

⭐ SESSION 25 • COMPLETED
Derived Tables in FROM
SELECT o.order_id, d.item_rev
FROM sales.orders o
JOIN (
  SELECT order_id, SUM(net_amount) AS item_rev
  FROM sales.order_items GROUP BY order_id
) d ON o.order_id = d.order_id;

Pre-aggregated child records into an isolated inline derived table at order grain, preventing 1:N join fan-out data duplication.

🔄 SESSION 26 • THE MISSION
Correlated Subqueries & EXISTS
SELECT e.employee_id, e.salary
FROM stores.employees e
WHERE e.salary > (
  SELECT AVG(e2.salary)
  FROM stores.employees e2
  WHERE e2.dept_id = e.dept_id
);

Reference outer row attributes dynamically (e.dept_id) to evaluate relative peer benchmarks and short-circuit boolean checks.

🚀
The Core Evolution: Derived tables evaluate strictly on their own; they cannot 'see' outer tables. Correlated subqueries open an outer scope window, parameterizing inner logic per row.

Bridging Concept

Emphasize scope visibility. In derived tables, the subquery executes independently first. In correlated subqueries, the inner query references outer columns.

🔄
The Department Bonus Crisis FLAT GLOBAL BENCHMARK • ₹34.8 LAKH INCENTIVE DISTORTION
EXAMPLE STORY • NAMES & NUMBERS MADE UP
₹34.8 Lakh Bonus Distortion
SubPlan Correlated Scan
100% Peer Fairness
STEP 01 • THE FLAT BENCHMARK
junior-hr-analyst Annual Review
“I filtered employees earning above average salary using an uncorrelated subquery comparing all staff to the company global average of ₹63,273.60.”
The query evaluated one global constant across completely different job families and department pay bands.
STEP 02 • BENCHMARK BIAS
💥 ₹34.8 Lakh Bonus Distortion
Budget Bias
High-salary Engineering staff captured 92% of incentive bonuses, while star Operations managers received ₹0 despite record fulfillment throughput!
💥 Global Benchmark Blindness
InitPlan Flaw
Uncorrelated subqueries evaluate once at startup (InitPlan). They cannot adapt to varying department baseline averages.
STEP 03 • CORRELATED SUBPLAN
CORRELATED
🔄 Peer-Relative Bonus Allocation
SELECT e.employee_id, e.dept_id, e.salary
FROM stores.employees e
WHERE e.salary > (
  SELECT AVG(sub.salary)
  FROM stores.employees sub
  WHERE sub.dept_id = e.dept_id
);
-- Correlated SubPlan restores equity!
✓ Evaluated Per Department 100% Peer Fairness
STEP 04 • CORE PRINCIPLE Global benchmarks distort business reality. When qualifying entities against peer cohorts, correlate the inner subquery to the outer entity's category key.

Story Coaching

Set up the emotional stakes: explain how rewarding employees based on flat global averages caused warehouse managers to quit. Then reveal how one WHERE clause restored equity.

From Story → SQL: The Correlated Execution Lifecycle

How PostgreSQL binds outer tuple references and executes parameterized subplans.

Phase 01
Outer Scan & Bind
The engine reads a candidate row from stores.employees e and extracts its department key (e.g. dept_id = 1).
Phase 02
Parameterized SubPlan
The inner subquery evaluates with the parameter substituted: SELECT AVG(salary) WHERE dept_id = 1 (₹67,489.22).
Phase 03
Predicate Evaluation
The outer row's salary is compared against its own department average. If greater, the row is emitted to the output buffer.
⚙️
Execution Model: Uncorrelated subqueries execute once at query start (InitPlan). Correlated subqueries execute dynamically per candidate row (SubPlan), behaving like a for-each loop over outer candidate tuples.

Lifecycle Walkthrough

Walk through employee 2451 (Henry Ganguly, dept 1, salary ₹2,42,825). Show that Henry qualifies against dept 1 average (₹67,489.22).

Visual Studio: The Correlated Execution Engine

Click execution modes below to contrast naive row-by-row nested loop evaluation against planner optimizations.

CORRELATED NESTED LOOP • ROW-BY-ROW OUTER BINDING
Outer Row #2451 (dept_id=1, Henry Ganguly) → Inner: SELECT AVG(salary) WHERE dept_id=1 → ₹67,489.22
Iterative Parameter Passing: The inner subquery is physically re-executed for each outer candidate tuple. The outer column reference binds dynamically at runtime.
Step 01
Outer Tuple Read
PostgreSQL reads candidate outer row e and extracts its correlation column values.
Step 02
SubPlan Substitution
The inner query is executed with the outer variable substituted into its WHERE clause.
Step 03
Index Advice
Today RetailMart uses PK indexes only; in production schemas, secondary B-tree indexes turn scans into fast seeks.

Visual Demonstration

Toggle between mode 1 (SubPlan loop) and mode 2 (Derived Table alternative). Point out that scalar WHERE subqueries do not unnest into semi-joins, and discuss production indexing advice.

Definition: Correlated Subquery Syntax & Rules

Binding inner query filters to outer table aliases to calculate relative peer thresholds.

Peer-Relative Compensation Filter ▸ Run in Playground
SELECT
  employee_id,
  first_name,
  last_name,
  dept_id,
  salary
FROM stores.employees e
WHERE salary > (
  SELECT AVG(salary)
  FROM stores.employees
  WHERE dept_id = e.dept_id
)
ORDER BY dept_id ASC, salary DESC, employee_id ASC
LIMIT 10;
Rule 01
Outer Table Alias
The outer table must be assigned an alias (e.g. stores.employees e) so inner clauses can unambiguously reference its columns.
Rule 02
Correlation Predicate
The inner query must contain a condition referencing the outer alias: WHERE inner.dept_id = e.dept_id.
Rule 03
Scalar Output Guarantee
When used with scalar comparison operators (>, =), the subquery must emit exactly one row and one column.
Rule 04
SubPlan Planner Node
In EXPLAIN output, correlated subqueries appear as SubPlan 1, confirming dynamic per-row execution.

Syntax Breakdown

Point out e.dept_id inside the inner subquery. Explain that this is what makes the subquery correlated rather than self-contained.

Visual Studio: The EXISTS Predicate & Short-Circuiting

Contrast instant short-circuit boolean checks against full-set membership scans.

EXISTS SEMI-JOIN • PRESERVES 1 ROW PER ENTITY (27,674 CUSTOMERS)
One match is enough → Emits 1 row per customer → 27,674 high-value customers
Semi-Join Efficiency: For Scene 9 (net_total ≥ ₹1,00,000), EXISTS emits exactly 27,674 customer rows without duplicates. In contrast, an INNER JOIN fans out to 40,434 rows. Note: on PostgreSQL, IN (subquery) plans identically to EXISTS as a Merge/Hash Semi Join; the real trap is NOT IN with NULLs.
Advantage 01
Instant Short-Circuit
Execution halts on row #1. Does not scan additional child rows for the customer.
Advantage 02
Zero Fan-Out
Customer entities are never duplicated. Eliminates the need for expensive SELECT DISTINCT deduplication.
Advantage 03
Optimizer Semi-Join
PostgreSQL frequently unnests correlated EXISTS queries into high-speed Hash Semi-Joins automatically.

Short-Circuit Deep Dive

Teach 'one match is enough, 1 row per customer'. EXISTS returns 47,521 customers vs 1,50,000 orders in INNER JOIN. For Scene 9, EXISTS yields 27,674 customers vs 40,434 join rows. IN and EXISTS plan identically as semi-joins.

Definition: EXISTS Syntax & Semi-Join Mechanics

Testing row existence without fan-out cartesian multiplication or memory-heavy deduplication.

High-Value Customer Semi-Join ▸ Run in Playground
SELECT
  c.customer_id,
  c.first_name,
  c.last_name,
  c.tier
FROM customers.customers c
WHERE EXISTS (
  SELECT 1
  FROM sales.orders o
  WHERE o.cust_id = c.customer_id
    AND o.net_total >= 100000
)
ORDER BY c.customer_id ASC
LIMIT 10;
Concept 01
Boolean Return Value
EXISTS evaluates strictly to TRUE or FALSE. It never returns data rows or column values to the outer query.
Concept 02
SELECT 1 Convention
Writing SELECT 1 signals that columns do not matter. The optimizer ignores the projection list completely.
Concept 03
Grain Preservation
Unlike an INNER JOIN to orders, EXISTS never duplicates customer records, preserving the 1-row-per-customer grain.
Concept 04
Semi-Join Planner Node
PostgreSQL 18 plans this query as a Merge Semi Join or Hash Semi Join, achieving single-pass execution.

Teaching Note

Address the common interview myth: 'SELECT 1 is faster than SELECT * in EXISTS'. Explain that PostgreSQL's optimizer treats them identically.

Visual Studio: NOT EXISTS vs NOT IN (The NULL Shield)

Understanding why three-valued logic breaks NOT IN, and why NOT EXISTS is completely immune.

NOT EXISTS • 2VL BOOLEAN IMMUNITY (2,479 ROWS)
NOT EXISTS checks presence: 0 matching rows found → returns TRUE → 2,479 inactive accounts
NULL-Safe Anti-Join: NOT EXISTS evaluates whether at least one tuple matches. When zero rows match, it evaluates strictly to TRUE, completely immune to NULL values.
2VL Logic
NOT EXISTS Shield
Checks whether qualifying child rows exist. If 0 rows match, evaluates strictly to TRUE regardless of nullability.
3VL Trap
NOT IN Catastrophe
If the child result contains even one NULL (e.g. a guest checkout with NULL cust_id), val != NULL yields UNKNOWN, silently collapsing the entire output to zero rows.
Optimizer Plan
Hash Anti Join
PostgreSQL compiles NOT EXISTS directly into an optimal in-memory Hash Anti Join, scanning the child table once.

The NULL Trap

This is intermediate SQL's most dangerous trap: (x != 1 AND x != NULL) yields UNKNOWN. RetailMart cust_id has 0 NULLs today (NOT IN returns 2,479); but a single guest NULL drops NOT IN to 0 rows, while NOT EXISTS remains immune.

Definition: Anti-Join Safety via NOT EXISTS

Isolating non-matching parent records safely without three-valued logic vulnerabilities.

Dormant Customer Anti-Join ▸ Run in Playground
SELECT
  c.customer_id,
  c.first_name,
  c.last_name,
  c.tier
FROM customers.customers c
WHERE NOT EXISTS (
  SELECT 1
  FROM sales.orders o
  WHERE o.cust_id = c.customer_id
)
ORDER BY c.customer_id ASC
LIMIT 10;
Syntax 01
NOT EXISTS Predicate
Reverses the boolean existence check: emits the outer candidate row if and only if the inner query returns zero records.
Syntax 02
NULL Immunity
Because it operates on set cardinality rather than value equality, NULLs inside the child table cannot nullify the outer result.
Syntax 03
Anti-Join Plan Nuance
Plan depends on column: LEFT JOIN ... WHERE o.cust_id IS NULL plans as a Hash Anti Join, while WHERE o.order_id IS NULL plans as Hash Right Join + Filter. NOT EXISTS plans as a clean Hash Anti Join either way (2,479 rows).
Syntax 04
Readability Superiority
Self-documenting business intent: "Select customers where there DOES NOT EXIST any order for that customer".

Engineering Best Practice

Advise students to adopt NOT EXISTS as their personal standard for anti-joins. It prevents subtle 3VL bugs that slip through code reviews.

Visual Studio: Relative Variance & Benchmark Columns

Decorating entity records with contextual peer baselines directly in the projection list.

METRIC VARIANCE • RELATIVE SPREAD (+₹82,348.38)
price - brand_avg_price = ₹1,46,498.94 - ₹64,150.56 = +₹82,348.38 Premium
Contextual Deviation: Subtracting the correlated cohort benchmark directly in SELECT isolates premium catalog pricing relative to peer brands. Product #146 (Sony Deserunt X) in Brand #3 (Sony) has catalog price ₹1,46,498.94 against brand average ₹64,150.56, creating a +₹82,348.38 premium spread.
Use Case 01
Baseline Decoration
Compute brand, category, or store benchmarks dynamically and display them directly on product catalog rows.
Use Case 02
Variance Calculation
Subtract the correlated benchmark from the base metric (price - (SELECT AVG...)) to measure premium spread.
Use Case 03
Latency Trade-Off
Correlated SELECT subqueries run per emitted row. Excellent for small filtered outputs; for large batches, use derived tables.

Projection Nuance

Demonstrate how having both the absolute metric (price) and relative benchmark (brand average) on the same row empowers business analysts.

Definition: Relative Benchmark Columns in SELECT

Projecting dynamic cohort averages and calculating row-level deviations in a single scan.

Brand Benchmark & Price Variance Calculation ▸ Run in Playground
SELECT
  p.product_id,
  p.product_name,
  p.brand_id,
  p.price,
  ROUND((
    SELECT AVG(p2.price)
    FROM products.products p2
    WHERE p2.brand_id = p.brand_id
  ), 2) AS brand_avg_price,
  ROUND(p.price - (
    SELECT AVG(p3.price)
    FROM products.products p3
    WHERE p3.brand_id = p.brand_id
  ), 2) AS price_variance
FROM products.products p
ORDER BY price_variance DESC, p.product_id ASC
LIMIT 10;
Technique 01
Scalar Subquery in SELECT
Placing a correlated subquery inside the SELECT projection list generates a dynamic computed column per row.
Technique 02
Inline Arithmetic
Outer attributes and inner scalar subqueries can be combined using standard math operators (e.g. price - (SELECT ...)).
Technique 03
Mandatory Alias
Always assign an explicit column alias (AS brand_avg_price) so client applications receive a clean column header.
Technique 04
Volume Discipline
For reporting queries on lakhs of rows, prefer pre-aggregating in a Session 25 derived table to avoid redundant SubPlan execution.

Architecture Advice

Teach the architectural rule of thumb: correlated SELECT subqueries are fine for filtered UI views (LIMIT 20); use derived tables for batch pipelines.

Common Mistakes: Correlated Subquery Pitfalls

Avoid the four most frequent anti-patterns encountered in correlated subquery engineering.

01
Missing Outer Table Alias
Writing WHERE dept_id = dept_id inside the subquery binds to the inner table itself, causing a 1=1 tautology rather than a correlation.
02
The 3VL NOT IN NULL Trap
Using NOT IN (SELECT nullable_col) returns zero rows the moment a single NULL exists. Always use NOT EXISTS instead.
03
Unindexed SubPlan Scans
Writing correlated subqueries over lakhs of rows on unindexed columns forces a full sequential table scan per outer row.
04
JOIN + DISTINCT Overkill
Joining parent to child just to filter parent records creates massive fan-out duplicates that require expensive sorting to remove. EXISTS preserves parent grain naturally.
🛡️
Defense Strategy: Always verify that correlated join predicates reference indexed foreign keys, and default to NOT EXISTS for anti-join queries.

Teaching Anchor

Warn students about testing inner queries alone: beginners often think their query is broken when pgAdmin complains about the missing outer table.

▶ Enter Practice Arena

Gateway Transition

Transition students from theory to live coding drills in the interactive practice arena.

Practice Arena: Correlated Subqueries & EXISTS

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

Practice Arena Live Drills

Give students 15 minutes to complete the 4 challenges. Circulate and check whether they remember to correlate inner WHERE clauses to outer aliases.

Interview Masterclass: Correlated Subqueries & EXISTS

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

01 • SubPlan vs InitPlan
02 • SELECT 1 in EXISTS
03 • 3VL NOT IN Trap
04 • Semi-Join Unnesting
05 • Correlated in SELECT
06 • NOT EXISTS vs LEFT JOIN
07 • Cardinality Errors
08 • Scope Bubbling
PLANNER EXECUTION
“What is the physical difference between an InitPlan and a SubPlan in PostgreSQL?”
An InitPlan represents an uncorrelated subquery that runs exactly once at startup; its result is cached and substituted as a constant.

A SubPlan represents a correlated subquery whose execution depends on outer row variables. It must re-execute for each outer tuple unless the optimizer can decorrelate it into a join.
Interview Trap: Assuming all subqueries execute once. Correlating on an unindexed column causes N full table scans, resulting in severe latency regressions.

Interview Coaching

Have students practice explaining Question 3 (3VL NOT IN Trap). It is one of the most common senior SQL interview questions.

Self-Check: 10 Master Flashcards

Click cards to test your retention of outer query correlation, boolean EXISTS tests, and anti-join mechanics.

What makes a subquery correlated rather than uncorrelated?
Outer Variable Reference! An inner WHERE or SELECT clause references a column alias from the outer query.
What is the difference between an InitPlan and a SubPlan in EXPLAIN?
InitPlan runs once at startup and caches the value; SubPlan re-executes dynamically per outer candidate row.
Why does EXISTS short-circuit upon finding the first matching row?
Boolean Semantics! EXISTS only tests for row existence (TRUE/FALSE); scanning further matching child rows is unnecessary.
Why is 'SELECT 1' conventionally written inside EXISTS instead of 'SELECT *'?
Developer Convention! The query planner ignores the projection list completely; both execute identically.
Why does NOT IN return zero rows when the inner subquery contains a NULL?
Three-Valued Logic (3VL)! val != NULL evaluates to UNKNOWN, collapsing the entire AND condition to UNKNOWN.
Why is NOT EXISTS completely immune to the NULL trap?
Set Cardinality Check! NOT EXISTS checks whether matching rows count = 0, evaluating strictly to TRUE or FALSE.
What happens if a correlated scalar subquery in WHERE returns 2 rows?
Fatal Runtime Error! Scalar comparisons require exactly 1 row; returning 2+ rows halts execution immediately.
How does PostgreSQL optimize an unnested EXISTS subquery?
Semi-Join! The planner flattens correlated EXISTS into an in-memory Hash Semi-Join or Merge Semi-Join.
Can a correlated subquery be placed inside the SELECT projection list?
YES! It acts as a scalar expression computing relative cohort benchmarks (e.g. brand average price) per row.
When should you avoid correlated subqueries in favor of derived tables?
Large Batch Aggregations! Over lakhs of rows, pre-aggregating in FROM avoids repeated SubPlan evaluations.

Self-Check Review

Review card 2 (short-circuiting) and card 5 (3VL NOT IN trap). Both are critical for writing bug-free production queries.

Key Takeaways: The 6 Laws of Correlated Execution

Master these six rules to structure performant, bug-free dynamic subqueries in PostgreSQL.

01
Dynamic Outer Binding
Inner queries reference outer aliases to evaluate conditions row-by-row relative to the candidate tuple.
02
One Match Is Enough
EXISTS needs only one qualifying row per outer row, so it never multiplies rows: each customer comes back once, however many orders they have.
03
Zero Fan-Out Guarantee
Semi-joins filter parent entities without joining child rows, eliminating duplicate row explosion and DISTINCT sorting.
04
The NULL Shield
Always use NOT EXISTS for anti-joins. Never use NOT IN on nullable columns due to 3VL collapse.
05
Index Correlated Keys
Index inner foreign keys in production to turn repeated SubPlan table scans into instant B-tree seeks.
06
Contextual Metrics
Use correlated scalar subqueries in SELECT to decorate entities with cohort baselines and relative variance metrics.

Takeaways Summary

Have students snapshot this slide: it is the comprehensive mental cheat sheet for correlated execution and semi-join architecture.

Quick Reference: Correlated Subqueries & EXISTS Syntax

A production syntax reference card for dynamic correlation, semi-joins, and anti-joins.

Master Correlated Reference Query ▸ Run in Playground
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  e.dept_id,
  ROUND(e.salary, 2) AS salary,
  ROUND((
    SELECT AVG(e2.salary)
    FROM stores.employees e2
    WHERE e2.dept_id = e.dept_id
  ), 2) AS dept_avg_salary,
  ROUND(e.salary - (
    SELECT AVG(e3.salary)
    FROM stores.employees e3
    WHERE e3.dept_id = e.dept_id
  ), 2) AS dept_variance
FROM stores.employees e
WHERE EXISTS (
  SELECT 1
  FROM stores.employees e_peer
  WHERE e_peer.dept_id = e.dept_id
    AND e_peer.salary > e.salary
)
ORDER BY e.dept_id ASC, e.salary DESC, e.employee_id ASC
LIMIT 10;
WHERE Slot
Correlated Filter
WHERE col > (SELECT AVG(...) WHERE sub.k = out.k)
Filters candidate rows against cohort benchmarks.
EXISTS Slot
Short-Circuit Semi-Join
WHERE EXISTS (SELECT 1 FROM child c WHERE c.k = p.k)
Tests child presence without row fan-out.
NOT EXISTS Slot
NULL-Safe Anti-Join
WHERE NOT EXISTS (SELECT 1 FROM ...)
Isolates non-matching rows immune to 3VL NULL collapse.
SELECT Slot
Dynamic Benchmark
(SELECT AVG(...) WHERE ...) AS cohort_avg
Decorates rows with contextual cohort averages.
Spread Slot
Inline Variance
val - (SELECT AVG(...) WHERE ...) AS variance
Measures row-level deviation from cohort peers.
Index Rule
Production Index
In production schemas, index foreign keys to turn sequential inner scans into fast B-tree lookups (Session 40).

Reference Usage

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

Take-Home Challenge: Enterprise Correlated Query Synthesis

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

CHALLENGE 01 • HR ANALYTICS

Above-Average Department Earners

Identify all employees who earn strictly more than the average salary of their own department using a correlated subquery.

Starter Template ▸ Run in Playground
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  e.dept_id,
  ROUND(e.salary, 2) AS salary
FROM stores.employees e
WHERE e.salary > (
  SELECT AVG(e2.salary)
  FROM stores.employees e2
  WHERE e2.dept_id = e.dept_id
)
ORDER BY e.dept_id ASC, e.salary DESC, e.employee_id ASC
LIMIT 10;
CHALLENGE 02 • CUSTOMER LIFECYCLE

Dormant Customer Isolation

Use NOT EXISTS to generate a verified roster of registered customers who have never placed a single order in sales.orders.

Starter Template ▸ Run in Playground
SELECT
  c.customer_id,
  c.first_name || ' ' || c.last_name AS customer_name,
  c.tier
FROM customers.customers c
WHERE NOT EXISTS (
  SELECT 1
  FROM sales.orders o
  WHERE o.cust_id = c.customer_id
)
ORDER BY c.customer_id ASC
LIMIT 10;
CHALLENGE 03 • MERCHANDISING

Brand Premium Price Variance

Project product catalog details alongside brand average price and price variance using correlated SELECT subqueries.

Tables: products.products • Benchmark: brand_id average • Metric: price - brand_avg
CHALLENGE 04 • VIP ACCOUNTS

High-Value Order Verification

Identify customers who have placed orders with net_total >= ₹1,00,000 using EXISTS to guarantee zero duplicate fan-out.

Tables: customers, orders • Filter: net_total >= 100000 • Pattern: EXISTS Semi-Join

Homework Guidance

Assign these 4 challenges for student practice before the next live session on LATERAL Joins.

Your SQL Journey: Module 3 Advanced Analytics!

Milestones across the 59-session master curriculum

✓ 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 • DERIVED TABLES
Subqueries II: Derived Tables in FROM
Pre-aggregating transactional grains, defending against fan-out, and multi-source virtual relations.
• SESSION 26 • YOU ARE HERE
Correlated Subqueries & EXISTS
Row-by-row outer referencing, fast semi-joins with EXISTS, and NULL-safe anti-joins.
🚀
Milestone Achieved: You have conquered row-by-row correlation, short-circuit boolean checking, and NULL-safe anti-joins. Next, we unlock the for-each loop of SQL: LATERAL joins!

Progress Anchor

Celebrate completing Session 26! Point out that they now possess the tools to solve complex peer-relative filtering and anti-joins.

Coming Next: Session 27 • LATERAL Joins (The For-Each Loop of SQL)

Unlocking dynamic subquery execution in the FROM clause with cross-referencing capabilities.

TOPIC 01
For-Each Subqueries in FROM
Pass outer row columns directly into FROM-clause subqueries to evaluate parameterized tables per parent row.
TOPIC 02
Top-N Per Group Queries
Solve the classic 'Top 3 orders per customer' or 'Top 2 products per category' problem with clean parameterized scans.
TOPIC 03
LEFT JOIN LATERAL ON true
Preserve parent entities even when their parameterized LATERAL subquery returns zero rows.
LATERAL Joins on Live Schedule → Review From Beginning ↺

Closing Remarks

Send students off with excitement for LATERAL joins in Session 27.

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