Subqueries Part 2 and LATERAL: practice questions
400 questions in four levels, all on RetailMart, the practice database of this course. Write every query yourself, get it wrong, read the error, fix it. That is how it sticks.
Answers are coming soon. Post your query in the WhatsApp Community or Discord and we will check it together.
Easy 100 questions Medium 100 questions Hard 100 questions Crazy 100 questions
Core syntax, applied directly
CORRELATED & LATERAL - CONCEPTUAL Q1 What is a correlated subquery? Q2 Difference between correlated and uncorrelated. Q3 What is LATERAL JOIN? Q4 CROSS JOIN LATERAL vs LEFT JOIN LATERAL? Q5 Why must LATERAL reference earlier FROM items? Q6 Performance: per-row evaluation. Q7 When is LATERAL the only correct choice? Q8 LATERAL + LIMIT for top-N per group. Q9 Compare correlated subquery in SELECT vs LATERAL in FROM. Q10 LATERAL with returning subquery vs LATERAL with table. Q11 LATERAL inside a CTE - allowed? Q12 LATERAL with generate_series. Q13 LATERAL with unnest. Q14 LATERAL with jsonb_array_elements. Q15 Why is LATERAL essential for top-N per partition pre-window functions? Q16 Does LATERAL fan-out? Q17 CROSS JOIN LATERAL with empty subquery - what happens? Q18 LEFT JOIN LATERAL with empty subquery? Q19 LATERAL in DELETE / UPDATE? Q20 Compare LATERAL vs row_to_json. Q21 LATERAL re-execution cost - index helps? Q22 LATERAL replacing scalar subquery - when faster? Q23 LATERAL replacing correlated subquery - when more readable. Q24 LATERAL with aggregate inside. Q25 LATERAL returning multiple columns + multiple rows. CORRELATED SUBQUERIES Q26 For each order, count of same-customer orders. Q27 For each customer, count of their orders. Q28 For each product, avg rating. Q29 For each store, count employees. Q30 For each campaign, total spend. Q31 For each customer, latest order_date. Q32 For each product, latest review. Q33 For each ticket, count comments. Q34 For each employee, latest pay_slip. Q35 For each shipment, customer email via correlated. Q36 Customers WHERE (subquery COUNT) > N. Q37 Customers WHERE EXISTS (correlated). Q38 Products WHERE (subquery AVG) < threshold. Q39 Orders WHERE net_total > correlated AVG by customer. Q40 Employees WHERE salary > correlated AVG by dept. Q41 Customers WHERE last_order > N days ago. Q42 Products WHERE last_review > N days ago. Q43 Tickets WHERE (correlated comment count) = 0. Q44 Reviews WHERE rating < (cust's avg rating). Q45 Orders WHERE net_total < (store's median). Q46 Correlated UPDATE: set tier_id = (subquery from loyalty). Q47 Correlated DELETE: delete orphan rows. Q48 Correlated EXISTS with extra filter. Q49 Correlated NOT EXISTS. Q50 Correlated subquery returning aggregate. LATERAL BASICS Q51 LATERAL: per customer, get count. Q52 LATERAL: per customer, get latest order. Q53 LATERAL: per product, get latest review. Q54 LATERAL: per store, get employee count. Q55 LATERAL: per campaign, get sum of spend. Q56 LATERAL: per region, get sum of revenue. Q57 LATERAL: per agent, get count of tickets. Q58 LATERAL: per warehouse, get latest snapshot. Q59 LATERAL: per supplier, get count of products. Q60 LATERAL: per courier, get avg delivery time. Q61 CROSS JOIN LATERAL vs LEFT JOIN LATERAL example. Q62 LATERAL returning multiple columns. Q63 LATERAL with WHERE inside. Q64 LATERAL with ORDER BY inside. Q65 LATERAL with LIMIT inside. Q66 LATERAL with aggregate function. Q67 LATERAL with no rows - INNER vs LEFT. Q68 LATERAL with generate_series. Q69 LATERAL with unnest array. Q70 LATERAL with jsonb_array_elements. Q71 LATERAL chain: A -> B -> C. Q72 LATERAL in subquery. Q73 LATERAL with conditional return. Q74 LATERAL with EXISTS check inside. Q75 LATERAL in CTE. TOP-N PER GROUP Q76 Per customer, top 3 orders by net_total. Q77 Per customer, latest 5 orders. Q78 Per customer, first 3 orders. Q79 Per region, top 5 stores by revenue. Q80 Per category, top 3 products by units. Q81 Per brand, top 5 products by sales. Q82 Per agent, top 3 tickets by priority. Q83 Per platform, top 5 campaigns by ROI. Q84 Per supplier, 3 most recent shipments. Q85 Per warehouse, top 5 products by quantity. Q86 Per dept, top 3 highest paid employees. Q87 Per store, employee with most tickets. Q88 Per call_reason, longest call. Q89 Per session, the URL visited last. Q90 Per cohort, top customer LTV. Q91 Per region, top 3 cities by orders. Q92 Per tier, top 5 by spend. Q93 Per category, top 3 brands by sales. Q94 Per warehouse, oldest snapshot. Q95 Per courier, fastest shipment. Q96 Per campaign, top attribution day. Q97 Per customer, last interaction (any source). Q98 Per product, first-buyer. Q99 Per agent, first-resolved ticket. Q100 Per region per month, top store. Combined ideas, multi-step thinking
DEEPER CONCEPTUAL Q1 When does Postgres unnest a correlated subquery to a JOIN? Q2 Why does LATERAL fan out the outer row? Q3 LATERAL with a subquery referencing 2 outer FROM items. Q4 Compare LATERAL JOIN ON TRUE vs CROSS JOIN LATERAL. Q5 LATERAL inside view definition - when problematic. Q6 Why is "Nested Loop with LATERAL" the common plan? Q7 Compare LATERAL to apply (SQL Server). Q8 LATERAL with parameterized subquery. Q9 Multi-LATERAL chain - each refers to previous. Q10 LATERAL + GROUP BY parent - interaction. Q11 LATERAL inside FROM (subquery). Q12 LATERAL inside RETURNING (INSERT/UPDATE). Q13 Compare LATERAL with COMPOSITE TYPE. Q14 LATERAL returning derived rows from function. Q15 Why is LATERAL slow without right index? Q16 LATERAL + window inside subquery. Q17 Compare LATERAL + LIMIT 1 vs DISTINCT ON. Q18 LATERAL semantic: 1 evaluation per outer row. Q19 LATERAL doesn't propagate ORDER BY of subquery to outer query. Q20 LATERAL with row constructor return. Q21 LATERAL + UNION ALL. Q22 LATERAL + EXISTS. Q23 LATERAL + NOT EXISTS. Q24 LATERAL with conditional subquery. Q25 LATERAL with recursive CTE inside. CORRELATED DEEPER Q26 Correlated SELECT with 5 metrics per customer. Q27 Correlated MIN/MAX. Q28 Correlated PERCENTILE per group. Q29 Correlated COUNT FILTER. Q30 Correlated with multi-column join. Q31 Correlated AS view-like inline. Q32 Correlated subquery with EXISTS chain. Q33 Correlated NOT EXISTS chain. Q34 Correlated in HAVING. Q35 Correlated in ORDER BY. Q36 Correlated in WHERE returning 0 or 1. Q37 Correlated returning ARRAY. Q38 Correlated returning JSON. Q39 Correlated returning composite type. Q40 Correlated for "find prior event". Q41 Correlated for "find next event". Q42 Correlated for "is currently active". Q43 Correlated for "is delinquent". Q44 Correlated for "is fraud-risk". Q45 Correlated for "tier-upgrade eligible". Q46 Correlated for "churn-risk". Q47 Correlated for "loyalty member". Q48 Correlated for "lifetime stage". Q49 Correlated for "premium-customer flag". Q50 Correlated for "geo-zone tag". LATERAL CHAINS Q51 LATERAL 1 -> LATERAL 2 (sequential dependency). Q52 LATERAL 1 -> LATERAL 2 -> LATERAL 3. Q53 LATERAL with parent + grandparent ref. Q54 LATERAL with multiple subqueries in one row. Q55 LATERAL with conditional return. Q56 LATERAL with CTE inside subquery. Q57 LATERAL with set ops inside. Q58 LATERAL with window inside. Q59 LATERAL with aggregate + group inside. Q60 LATERAL with EXISTS + CASE. Q61 LATERAL with derived calendar. Q62 LATERAL with date series. Q63 LATERAL with array_agg. Q64 LATERAL with jsonb_object_agg. Q65 LATERAL with multi-column ORDER BY. Q66 LATERAL "top-3 per group + total". Q67 LATERAL "first non-null". Q68 LATERAL with NULL handling. Q69 LATERAL "is_above_avg" via inline. Q70 LATERAL with multi-table subquery JOIN. Q71 LATERAL with EXCEPT inside. Q72 LATERAL with UNION inside. Q73 LATERAL with HAVING inside. Q74 LATERAL with GROUP BY ROLLUP inside. Q75 LATERAL with PERCENTILE inside. LATERAL + WINDOW COMBO Q76 LATERAL with ROW_NUMBER inside subquery. Q77 LATERAL with RANK inside. Q78 LATERAL with NTILE. Q79 LATERAL with LAG/LEAD. Q80 LATERAL with FIRST_VALUE / LAST_VALUE. Q81 LATERAL with PERCENT_RANK. Q82 LATERAL with CUME_DIST. Q83 LATERAL with running SUM. Q84 LATERAL with running AVG. Q85 LATERAL with moving window. Q86 LATERAL with partition-by-customer + ORDER BY. Q87 LATERAL with "first event in window". Q88 LATERAL with "n-th event in window". Q89 LATERAL with "last event in window". Q90 LATERAL with "delta vs previous". Q91 LATERAL with "delta vs first". Q92 LATERAL with "rank within group". Q93 LATERAL with "rank within tier + region". Q94 LATERAL with "percentile within cohort". Q95 LATERAL "year-over-year compare". Q96 LATERAL "month-over-month compare". Q97 LATERAL "rolling 7-day". Q98 LATERAL "rolling 30-day". Q99 LATERAL "rolling 90-day". Q100 LATERAL + 5-metric per-row computation. Interview grade, edge cases
LATERAL + SET OPS Q1 LATERAL with UNION ALL inside. Q2 LATERAL with INTERSECT inside. Q3 LATERAL with EXCEPT inside. Q4 Per customer, union of orders + reviews + tickets via LATERAL. Q5 Per product, all event types via LATERAL UNION. Q6 Per region, sum of revenue + spend via LATERAL UNION ALL. Q7 Per agent, intersection of ticket and call customers. Q8 Per supplier, products NOT in any order via LATERAL EXCEPT. Q9 Per category, brands present in BOTH high+low revenue cohorts. Q10 Per tier, count customers in each lifecycle via LATERAL UNION. Q11 Per campaign, attribution + spend in single row via LATERAL UNION. Q12 Per warehouse, in+out inventory deltas via LATERAL. Q13 Per courier, success rate via LATERAL counts. Q14 Per customer, "first 5 + last 5 orders". Q15 Per product, top + bottom rated review. Q16 Per region, top + bottom store revenue. Q17 Per dept, top + bottom salary employee. Q18 Per session, first + last page_view. Q19 Per ticket, first + last comment. Q20 Per call, transcript + sentiment in same row. Q21 LATERAL + ROLLUP inside. Q22 LATERAL + CUBE inside. Q23 LATERAL + GROUPING SETS inside. Q24 LATERAL + FILTER inside. Q25 LATERAL + HAVING inside subquery. PERFORMANCE Q26 EXPLAIN a slow correlated subquery. Q27 Rewrite to LATERAL - compare plans. Q28 Rewrite to window - compare plans. Q29 Add index for LATERAL subquery. Q30 Index FK columns for fast LATERAL. Q31 Use partial index for LATERAL filter. Q32 Use expression index. Q33 Pre-aggregate via CTE for LATERAL inner. Q34 Force Nested Loop with LATERAL. Q35 Force Hash Join (disable nestloop). Q36 Increase work_mem for LATERAL aggregates. Q37 Reduce subquery output to needed columns. Q38 Use LIMIT to bound LATERAL fan-out. Q39 Replace SELECT * with SELECT cols inside LATERAL. Q40 Diagnose "no rows from LATERAL" - verify ON clause. Q41 Compare CROSS JOIN LATERAL vs LEFT JOIN LATERAL - performance. Q42 LATERAL inside view - composability cost. Q43 LATERAL inside materialized view - caching benefits. Q44 LATERAL with parallel scan - when possible. Q45 LATERAL with partition-wise join. Q46 LATERAL with prepared statement. Q47 LATERAL with EXPLAIN ANALYZE breakdown. Q48 Drop unused LATERAL (single-value can be scalar subquery). Q49 Monitor LATERAL via pg_stat_statements. Q50 Anti-pattern: LATERAL in ORDER BY (slow). ANTI-PATTERNS Q51 ANTIPATTERN: LATERAL for a single-value (use scalar subquery). Q52 ANTIPATTERN: LATERAL with no index on FK. Q53 ANTIPATTERN: LATERAL returning entire row. Q54 ANTIPATTERN: LATERAL in WHERE clause as predicate. Q55 ANTIPATTERN: Correlated subquery instead of LATERAL when ORDER BY+LIMIT needed. Q56 ANTIPATTERN: LATERAL fanning out 1B rows. Q57 ANTIPATTERN: LATERAL + GROUP BY parent on fan-out result. Q58 ANTIPATTERN: LATERAL with random() - non-deterministic. Q59 ANTIPATTERN: LATERAL with now() - re-evaluated. Q60 ANTIPATTERN: LATERAL with side effects (volatile function). Q61 ANTIPATTERN: LATERAL returning too many columns. Q62 ANTIPATTERN: LATERAL when JOIN suffices. Q63 ANTIPATTERN: Correlated subquery in DML loop. Q64 ANTIPATTERN: Correlated subquery in JOIN ON. Q65 ANTIPATTERN: Correlated subquery without index. Q66 ANTIPATTERN: Mutating function in LATERAL. Q67 ANTIPATTERN: LATERAL hiding fan-out from later aggregates. Q68 ANTIPATTERN: LATERAL in CTE without MATERIALIZED hint. Q69 ANTIPATTERN: LATERAL with complex ORDER BY (sort cost). Q70 ANTIPATTERN: LATERAL with non-deterministic ORDER BY. Q71 ANTIPATTERN: LATERAL + window in same query. Q72 ANTIPATTERN: LATERAL with WHERE TRUE only. Q73 ANTIPATTERN: LATERAL with CROSS JOIN on outer cols. Q74 ANTIPATTERN: LATERAL when GROUP BY parent would aggregate. Q75 ANTIPATTERN: LATERAL as the only way (refactor opportunity). REAL PRODUCTION Q76 Build a "customer top-3 events" report. Q77 Build "product latest review + first review" report. Q78 Build "store top-N employees" report. Q79 Build "region monthly top sellers". Q80 Build "category breadcrumb + product top-3". Q81 Build "supplier top shipments + count". Q82 Build "campaign attribution + ROI". Q83 Build "warehouse low-stock + reorder suggestions". Q84 Build "agent leaderboard". Q85 Build "courier scorecard". Q86 Build "tier members + their top order". Q87 Build "loyalty redemptions + remaining balance". Q88 Build "RFM + LATERAL top product" report. Q89 Build "customer journey via LATERAL chain". Q90 Build "marketing funnel via LATERAL". Q91 Build "return reason analysis via LATERAL". Q92 Build "ticket SLA via LATERAL". Q93 Build "call category mix via LATERAL". Q94 Build "review sentiment via LATERAL". Q95 Build "anomaly detector via LATERAL". Q96 Build "outlier finder via LATERAL". Q97 Build "cohort retention via LATERAL". Q98 Build "churn predictor via LATERAL". Q99 Build "executive dashboard via LATERAL chain". Q100 Master: combine LATERAL + window + set ops + recursive in 1 query. Production scenarios, optimisation
LATERAL + RECURSIVE Q1 LATERAL with recursive CTE inside. Q2 Recursive depth bounded by LATERAL. Q3 LATERAL with recursive graph walk. Q4 LATERAL with hierarchy traversal. Q5 LATERAL with category tree walk. Q6 LATERAL with manager chain. Q7 LATERAL with friend-of-friend. Q8 LATERAL with BOM (bill of materials). Q9 LATERAL with dependency chain. Q10 LATERAL with cycle detection. Q11 LATERAL with shortest path. Q12 LATERAL with date series generation. Q13 LATERAL with calendar generation. Q14 LATERAL with Fibonacci/recursive numerics. Q15 LATERAL with rolling-window via recursive. Q16 LATERAL with "next N events". Q17 LATERAL with "prev N events". Q18 LATERAL with "find all ancestors". Q19 LATERAL with "find all descendants". Q20 LATERAL with depth-limit recursive. Q21 LATERAL with state-machine traversal. Q22 LATERAL with state-history rollup. Q23 LATERAL with version chain. Q24 LATERAL with audit-trail traversal. Q25 Master: LATERAL with recursive top-N. LATERAL + WINDOW MEGA Q26 LATERAL with PERCENTILE inside. Q27 LATERAL with MODE inside. Q28 LATERAL with cohort RFM scoring. Q29 LATERAL with rolling 7-day. Q30 LATERAL with rolling 30-day. Q31 LATERAL with EWMA. Q32 LATERAL with seasonality compare. Q33 LATERAL with YoY growth. Q34 LATERAL with regression slope. Q35 LATERAL with correlation. Q36 LATERAL with z-score. Q37 LATERAL with outlier flagging. Q38 LATERAL with anomaly detect. Q39 LATERAL with running rank. Q40 LATERAL with cumulative count. Q41 LATERAL with cumulative distinct. Q42 LATERAL with cumulative sum. Q43 LATERAL with rolling avg. Q44 LATERAL with rolling median. Q45 LATERAL with first/last value. Q46 LATERAL with LAG/LEAD chain. Q47 LATERAL with PARTITION BY tier. Q48 LATERAL with PARTITION BY region. Q49 LATERAL with PARTITION BY month. Q50 LATERAL with multi-PARTITION. LATERAL CHAINS 4-5 LEVELS Q51 customer -> last order -> first item -> product -> brand. Q52 region -> top store -> top employee -> top ticket. Q53 campaign -> top platform -> top customer -> top order. Q54 warehouse -> top product -> top supplier -> latest shipment. Q55 tier -> top customer -> top product -> top brand. Q56 agent -> top ticket -> customer -> top order. Q57 category -> top brand -> top product -> top buyer. Q58 courier -> busiest day -> top customer -> top order. Q59 dept -> top employee -> top ticket -> resolution time. Q60 supplier -> top product -> top warehouse -> quantity. Q61 month -> top region -> top store -> top customer. Q62 day -> top hour -> top order -> top product. Q63 brand -> top product -> top customer -> repeat purchases. Q64 region -> top city -> top customer -> top product. Q65 tier -> top member -> latest redemption -> product redeemed. Q66 campaign -> top platform -> top creative -> top attribution. Q67 session -> first url -> last url -> conversion event. Q68 story -> orders -> items -> shipment -> delivery. Q69 customer -> loyalty member -> tier -> next-tier delta. Q70 order -> payment -> fraud-check -> status -> refund. Q71 agent -> ticket -> comment -> resolution. Q72 ticket -> customer -> past orders -> past reviews. Q73 order -> return -> refund -> audit_log. Q74 page_view -> session -> cart -> checkout -> order. Q75 customer -> 5 events -> 5 derived metrics -> score. PRODUCTION MEGA Q76 Customer 360deg via LATERAL chain. Q77 Product 360deg via LATERAL chain. Q78 Region 360deg via LATERAL chain. Q79 Campaign 360deg via LATERAL chain. Q80 Store 360deg via LATERAL chain. Q81 Brand 360deg via LATERAL chain. Q82 Supplier 360deg via LATERAL chain. Q83 Agent 360deg via LATERAL chain. Q84 Courier 360deg via LATERAL chain. Q85 Tier 360deg via LATERAL chain. Q86 Warehouse 360deg via LATERAL chain. Q87 Department 360deg via LATERAL chain. Q88 Employee 360deg via LATERAL chain. Q89 Category 360deg via LATERAL chain. Q90 Channel 360deg via LATERAL chain. Q91 Executive dashboard via LATERAL mega. Q92 Operations dashboard via LATERAL. Q93 Marketing dashboard via LATERAL. Q94 Finance dashboard via LATERAL. Q95 HR dashboard via LATERAL. Q96 Cust service dashboard via LATERAL. Q97 Sales dashboard via LATERAL. Q98 Inventory dashboard via LATERAL. Q99 Supply chain dashboard via LATERAL. Q100 Master: LATERAL + recursive + window + set ops + DML in 1 mega query.