Joins Part 2: 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
JOINS PART 2 - CONCEPTUAL Q1 What is a SELF JOIN - and why do you need it? Q2 Why are aliases mandatory in self-joins? Q3 What is a FULL OUTER JOIN - when do both LEFT and RIGHT unmatched rows matter? Q4 Compare INNER vs LEFT vs RIGHT vs FULL - which rows each preserves. Q5 What is a CROSS JOIN - when do you actually want one? Q6 Difference between UNION and UNION ALL - and why ALL is faster. Q7 What is INTERSECT - when is it more readable than INNER JOIN? Q8 What is EXCEPT - and how is it different from anti-join? Q9 What rules must all queries in a UNION follow (column count, types)? Q10 Why does UNION sort + dedupe but UNION ALL does not? Q11 What is a LATERAL JOIN - give a one-line description. Q12 Compare LATERAL vs correlated subquery - same idea, different syntax. Q13 Can you SELF JOIN through a foreign key (manager -> employee)? Q14 Why is FULL OUTER JOIN often used in data reconciliation reports? Q15 What does CROSS JOIN with a numbers table give you? Q16 Does ORDER BY apply to each branch of UNION, or the combined result? Q17 Where do you put LIMIT in a UNION query - per branch or overall? Q18 What is "set semantics" vs "bag semantics" in SQL? Q19 Can NULLs match in INTERSECT? Q20 Why is FULL OUTER JOIN rarely used in OLTP queries? Q21 How is a SELF JOIN typically used to find pairs (e.g., "employees in the same department")? Q22 Compare CROSS JOIN vs FROM a, b - are they the same? Q23 Why is UNION often slower than a single SELECT with OR conditions? Q24 What is "generate_series" - and why does it pair so well with CROSS JOIN? Q25 When does EXCEPT ALL behave differently from EXCEPT? SELF JOIN BASICS Q26 Pairs of employees in the same dim_department (e1.dept_id = e2.dept_id, e1.id < e2.id). Q27 Pairs of customers in the same city. Q28 Pairs of orders placed by the same customer on the same day. Q29 Pairs of products with the same brand_id. Q30 Pairs of stores in the same region_id. Q31 List employees with the same role at different stores. Q32 Find customers who share the same email domain. Q33 List products in the same category with the same supplier_id. Q34 Find tickets with the same priority + same status - show paired ticket_ids. Q35 Pairs of campaigns running on the same platform. Q36 Pairs of pay_slips for the same employee but different salary_month. Q37 Pairs of orders by the same customer but different store_id. Q38 Pairs of reviews by the same customer on different products. Q39 Pairs of products with the same price_band (CASE-based). Q40 Pairs of warehouses in the same region (no region_id on warehouses? join via stores). Q41 SELF JOIN on customers: pairs of customers in same tier + same city. Q42 SELF JOIN: pairs of brands with same category_id. Q43 SELF JOIN: orders placed within 1 hour of each other by the same customer. Q44 SELF JOIN: shipments using the same courier_name on the same date. Q45 SELF JOIN: web_events.page_views in the same session_id. Q46 SELF JOIN: employees with same hire_date. Q47 SELF JOIN: pay_slips with same gross_salary but different employee_id. Q48 SELF JOIN: tickets created by same customer for different products. Q49 SELF JOIN: products with same supplier_id but different brand_id. Q50 SELF JOIN: campaigns with same budget but different platform. FULL OUTER + CROSS JOIN Q51 FULL OUTER JOIN customers and loyalty.members - show customers without loyalty AND members orphaned. Q52 FULL OUTER JOIN orders and shipments - orders without shipments + shipments without orders. Q53 FULL OUTER JOIN employees and pay_slips - employees never paid + pay_slips with no employee. Q54 FULL OUTER JOIN dim_region and stores - regions without stores + stores in no region. Q55 FULL OUTER JOIN dim_category and dim_brand - empty categories + brands with no category. Q56 FULL OUTER JOIN products and order_items - never-sold products + items pointing to deleted product. Q57 FULL OUTER JOIN warehouses and inventory_snapshots - empty warehouses + orphan snapshots. Q58 FULL OUTER JOIN tickets and support.agents - unassigned tickets + agents with no tickets. Q59 FULL OUTER JOIN ad_campaigns and ads_spend - campaigns with no spend + spend with no campaign. Q60 FULL OUTER JOIN reviews and orders - reviews not linked to order + orders never reviewed. Q61 CROSS JOIN dim_region x tiers - all (region, tier) combinations (potential customer segments). Q62 CROSS JOIN months x dim_category - all (month, category) buckets for revenue grid. Q63 CROSS JOIN device_type x os_list - all browser/device combinations. Q64 CROSS JOIN platforms x months - all reporting cells for ads_spend. Q65 CROSS JOIN dim_region x dim_brand - all marketxbrand combinations. Q66 CROSS JOIN generate_series(1, 12) x stores - month-by-store grid. Q67 CROSS JOIN order statuses x stores - every (status, store) bucket. Q68 CROSS JOIN ticket_priority x ticket_status - all priority-status combos. Q69 CROSS JOIN regions x campaigns - all targeting combinations. Q70 CROSS JOIN years x dim_department - year-by-dept HR grid. Q71 Use generate_series to build a date dimension. Q72 Build a calendar table (one row per day from 2024-01-01 to today) using generate_series. Q73 CROSS JOIN dim_category x tiers - used for cohort analysis grids. Q74 CROSS JOIN courier list x months - to see which courier-month combos had zero shipments. Q75 Single row x CROSS JOIN customers - turn a single row into N copies (uncommon but valid). UNION / INTERSECT / EXCEPT Q76 UNION ALL: combine customer emails and employee emails into one list (with source label). Q77 UNION ALL: all customer interactions - orders + reviews + tickets - into a single timeline. Q78 UNION: distinct cities from customers + stores combined. Q79 UNION ALL: combine domestic and international orders (if there were two tables). Use status='International' as proxy split. Q80 UNION ALL: shipment events + delivery events into one log. Q81 UNION ALL: agent activity from tickets + calls (preview for Topic 11). Q82 INTERSECT: customers who BOTH placed an order AND wrote a review. Q83 INTERSECT: customers in BOTH loyalty.members AND placed >0 orders. Q84 INTERSECT: products that appear in BOTH order_items AND reviews. Q85 INTERSECT: stores with BOTH employees AND orders. Q86 EXCEPT: customers who placed orders but are NOT in loyalty.members. Q87 EXCEPT: products with order_items but NO reviews. Q88 EXCEPT: employees with no pay_slip records. Q89 EXCEPT: stores with employees but no orders. Q90 EXCEPT: brands with products but no order_items linked. Q91 UNION ALL: top 5 highest-revenue + top 5 lowest-revenue products into one report. Q92 UNION ALL: count of orders this month + count last month + count YTD as 3 labelled rows. Q93 UNION ALL: per-region revenue + a grand-total row. Q94 UNION ALL: combine three priority lists (Critical, High, Medium) with a priority_label column. Q95 UNION ALL: registered customers + guest checkouts (where cust_id IS NULL) into one list. Q96 INTERSECT ALL vs INTERSECT - show difference using a duplicate-heavy column. Q97 UNION with ORDER BY at end - sort the combined result. Q98 UNION ALL + LIMIT - get top 3 from query A + top 3 from query B as 6 rows total. Q99 UNION ALL across three time buckets - last_week, last_month, last_quarter counts. Q100 UNION ALL: tickets + reviews + calls, all reduced to (customer_id, source, created_at). Combined ideas, multi-step thinking
SET OPS + SELF JOIN - CONCEPTUAL DEEPER Q1 Why is "self-join + GROUP BY" usually slower than a window function (preview)? Q2 How does a self-join scale with N - and when do you avoid it? Q3 When does FULL OUTER JOIN produce duplicate rows - and how do you collapse them with COALESCE? Q4 Why is CROSS JOIN with generate_series the standard way to "fill in missing dates"? Q5 Compare UNION ALL vs JOIN - when can the same answer be expressed either way? Q6 Why does UNION (without ALL) require a SORT step - and how does that affect plans? Q7 Compare EXCEPT vs NOT IN vs NOT EXISTS - three flavors of anti-join. Q8 What's the catch with INTERSECT and NULL columns? Q9 Why is FULL OUTER JOIN often the "reconciliation report" tool of choice? Q10 Explain what LATERAL JOIN does - and how it differs from a normal subquery. Q11 Why does LATERAL let you reference outer-row columns inside the subquery? Q12 When does the planner choose Hash Join vs Merge Join vs Nested Loop for self-joins? Q13 Compare LEFT JOIN LATERAL vs INNER JOIN LATERAL - when does each row get dropped? Q14 Why is SELF JOIN over a tiny table OK but a Cartesian on huge tables disastrous? Q15 Explain why ORDER BY in a UNION must appear ONLY at the end. Q16 What does GROUP BY 1 do in a UNION - does it apply to all branches? Q17 Why does generate_series often appear inside CROSS JOIN LATERAL? Q18 Compare CROSS JOIN unnest(array) vs LATERAL unnest(array). Q19 Why does UNION ALL preserve duplicates and how is that useful for "stacked timelines"? Q20 Walk through how SELF JOIN can compute "next event per row" before window functions. Q21 Why does FULL OUTER JOIN often require COALESCE on JOIN keys? Q22 Compare INTERSECT vs INNER JOIN ON all-columns - when are they equivalent? Q23 Why is EXCEPT sometimes preferred over LEFT JOIN ... IS NULL for "find missing" reports? Q24 What is "set semantics drift" - when a UNION quietly drops rows you wanted to keep? Q25 Why is FULL OUTER JOIN the standard "audit table mismatch" tool? SELF JOIN - DEEPER PATTERNS Q26 For each order, find the customer's PREVIOUS order (self-join on cust_id + ORDER BY). Q27 For each shipment, find the next shipment by the same courier_name. Q28 For each pay_slip, find the same employee's prior month pay_slip. Q29 For each ticket, find prior ticket by same customer (same cust_id). Q30 For each call, find prior call by same agent_id. Q31 For each review, find prior review by same customer for same product_id. Q32 For each page_view, find prior page_view in same session. Q33 Pairs of customers in same city, same tier - show how many such pairs exist. Q34 Find pairs of orders by same customer where time-difference < 1 hour. Q35 Self-join orders with itself: COUNT of repeat-day customers. Q36 For each campaign, find another campaign of same platform with higher budget. Q37 For each product, find another product of same brand with higher price. Q38 For each employee, find another employee of same role with higher salary. Q39 For each store, find another store in same region with higher order count. Q40 For each warehouse, find another warehouse in same region with higher quantity_on_hand. Q41 SELF JOIN employees: find employees whose hire_date is exactly N days after another employee. Q42 SELF JOIN orders: customers with 2+ orders within 7 days. Q43 SELF JOIN tickets: customers with 2+ tickets in same week. Q44 SELF JOIN reviews: customers who wrote 2 reviews on different products with same rating. Q45 SELF JOIN inventory: products whose quantity_on_hand at one warehouse = at another. Q46 SELF JOIN customers: pairs from same city with different tiers (cross-tier in same city). Q47 SELF JOIN orders: chains of 3+ same-day orders by same customer. Q48 SELF JOIN page_views: sessions where two page_views had same url. Q49 SELF JOIN tickets: ticket pairs from same customer where one is Critical and another Low. Q50 SELF JOIN products: products with same supplier_id and same category. FULL OUTER + CROSS JOIN GRIDS Q51 Full reconciliation: customers vs orders - show 4 buckets (both / customer only / order only / never). Q52 Full reconciliation: employees vs pay_slips - find pay_slips orphaned to deleted employees. Q53 Full reconciliation: orders vs payments - orders without payments + payments without orders. Q54 Full reconciliation: orders vs shipments - count of each side mismatch. Q55 Full reconciliation: loyalty.members vs customers - orphan members? Q56 Per region x month grid: SUM revenue (CROSS JOIN regions x month_series LEFT JOIN orders). Q57 Per platform x month grid: SUM ad spend (no zeros missing). Q58 Per ticket priority x month grid: COUNT tickets (zero-cell rows preserved). Q59 Per device_type x week grid: COUNT page_views. Q60 Per category x tier grid: COUNT distinct customers. Q61 Per courier x month grid: COUNT shipments. Q62 Per warehouse x day grid (last 7 days): quantity_on_hand. Q63 Per dim_department x month grid: total payroll. Q64 Per dim_region x dim_category grid: SUM revenue. Q65 Per status x month grid: order counts (all status x month combos shown). Q66 Use generate_series(2024-01-01, 2026-02-26, '1 month') + CROSS JOIN regions to build monthxregion target frame. Q67 CROSS JOIN tiers x dim_department to get "tier presence" matrix. Q68 CROSS JOIN dim_brand x dim_region: revenue matrix. Q69 CROSS JOIN courier list x order_status: shipment frequencies. Q70 CROSS JOIN log_level x service_name: counts. Q71 Build a calendar dimension (generate_series for dates) + week_of_year + is_weekend column. Q72 CROSS JOIN customers x campaigns to simulate "all campaigns reachable per customer" cell. Q73 CROSS JOIN dim_region x tiers x months - 3-dim grid for executive dashboard. Q74 CROSS JOIN every supplier x product to find supplier-product gaps. Q75 CROSS JOIN orders x generate_series - explode 1 order row into N (e.g., per installment). UNION / INTERSECT / EXCEPT / LATERAL Q76 UNION ALL: all touchpoints per customer (orders, reviews, tickets, calls) into one event stream. Q77 UNION ALL + GROUP BY: count of distinct customers across orders + reviews + tickets (deduped). Q78 UNION ALL: combined revenue stream from orders + ads_spend (sign-flip for spend). Q79 UNION ALL: combine top-5 best categories + bottom-5 worst categories with a label column. Q80 INTERSECT: customers who placed orders AND wrote reviews AND opened tickets. Q81 EXCEPT: products in inventory_snapshots but never in order_items. Q82 EXCEPT: customers ordered but never reviewed. Q83 EXCEPT: employees in stores.employees but not in pay_slips. Q84 INTERSECT: stores having BOTH employees AND orders AND inventory_snapshots. Q85 EXCEPT ALL vs EXCEPT: show difference on a duplicated cust_id list. Q86 UNION ALL: monthly revenue + monthly cost + monthly profit as separate rows with metric label. Q87 UNION ALL: registered + guest checkouts into uniform customer_id list. Q88 UNION ALL + ROLLUP-like: per-region totals + grand total via UNION. Q89 UNION ALL: rolling 12-week window built from 12 SELECTs (preview window functions). Q90 UNION ALL: ticket history + call history into a "support contact timeline" per customer. Q91 LATERAL: per customer, latest 3 orders (LATERAL with LIMIT 3 + ORDER BY). Q92 LATERAL: per product, latest review (LATERAL with LIMIT 1). Q93 LATERAL: per region, top 5 stores by revenue. Q94 LATERAL: per category, top 3 products by units sold. Q95 LATERAL with generate_series: explode orders into N installment rows. Q96 LATERAL: per customer, count distinct products purchased. Q97 LATERAL: per store, employee with highest salary. Q98 LATERAL: per courier_name, last 5 shipments. Q99 UNION ALL across 4 schemas (orders, reviews, tickets, calls) producing a unified "customer activity" denormalized feed. Q100 EXCEPT + LATERAL combined: find customers with orders but no reviews of those exact products. Interview grade, edge cases
ADVANCED JOIN PART 2 - CONCEPTUAL Q1 Walk through how LATERAL is planned: re-evaluated per outer row. Q2 Compare LATERAL LIMIT 1 vs DISTINCT ON for "latest per group". Q3 When is FULL OUTER JOIN's COALESCE(left.k, right.k) required vs optional? Q4 How does CROSS JOIN LATERAL generate_series produce "N rows per outer row" - explosion pattern. Q5 Compare self-join with window function performance (preview Topic 16). Q6 Explain how UNION ALL is a "stack vertically" while JOIN is "merge horizontally". Q7 When does INTERSECT use a Hash Aggregate vs Sort + Merge? Q8 Why is EXCEPT sometimes a better choice than NOT EXISTS for whole-row diffs? Q9 Explain "relational division" - every X who has ALL Ys - give a SQL recipe. Q10 Why are FULL OUTER JOINs the backbone of reconciliation (find rows missing on either side)? Q11 Walk through a 4-bucket reconciliation: both / only-left / only-right / neither. Q12 Compare a multi-condition self-join (a.x=b.x AND a.y<b.y) with a correlated subquery. Q13 Why does UNION ALL preserve duplicates while UNION removes them - and the cost difference. Q14 How do you build a "next event per row" with a self-join + NOT EXISTS gap check. Q15 Why do CROSS JOIN reports use ARRAY_AGG to build grids? Q16 Compare CROSS JOIN small x small x small vs CROSS JOIN huge x huge - performance cliff. Q17 Walk through "dense reporting" pattern: CROSS JOIN time x dim LEFT JOIN facts COALESCE 0. Q18 Why is LATERAL essential for "for each parent, get a subset of children with ORDER BY/LIMIT"? Q19 When does a SELF JOIN with composite key match patterns (a.x=b.x AND a.y<b.y)? Q20 Why does UNION drop information vs UNION ALL - and when is that desirable? Q21 Explain how INTERSECT can replace INNER JOIN + DISTINCT on all columns. Q22 Compare CROSS JOIN unnest(array) vs unnest in SELECT. Q23 What is "PIVOT" - how do you simulate it with FILTER + GROUP BY? Q24 What is "UNPIVOT" - how do you simulate it with UNION ALL? Q25 Walk through a "session attribution" query that requires LATERAL + set ops. LATERAL DEEP Q26 LATERAL: per customer, latest 5 orders. Q27 LATERAL: per product, latest 3 reviews (with rating). Q28 LATERAL: per region, top 5 stores by revenue. Q29 LATERAL: per category, top 3 products by units sold. Q30 LATERAL: per agent, latest 5 tickets resolved. Q31 LATERAL: per platform, top 3 campaigns by spend. Q32 LATERAL: per warehouse, oldest snapshot (product + date). Q33 LATERAL: per supplier, 3 most-recent shipments. Q34 LATERAL: per call_reason, longest call. Q35 LATERAL: per dept, highest-paid employee. Q36 LATERAL: explode order into installments (generate_series 1..3). Q37 LATERAL: explode shipment into "shipped -> in-transit -> delivered" steps. Q38 LATERAL: per customer, derive 12 monthly buckets (generate_series + LATERAL). Q39 LATERAL: per product, count of distinct buyers. Q40 LATERAL: per ticket, the same customer's PREVIOUS ticket. Q41 LATERAL + aggregation: per customer, JSON of all orders. Q42 LATERAL: per session, the page clicked just before checkout. Q43 LATERAL chain: per customer, last order -> that order's first item -> that item's product. Q44 LATERAL with WHERE that references outer row. Q45 LEFT JOIN LATERAL - keep outer row when subquery is empty. Q46 LATERAL + LIMIT 0 (no rows) - INNER excludes; LEFT keeps with NULLs. Q47 LATERAL with EXISTS - short-circuit detect. Q48 LATERAL with generate_series + interval - date-bucket per parent. Q49 LATERAL on a materialized view: top 3 products per category. Q50 LATERAL: per order, its top 3 line items by net_amount. SELF-JOIN ADVANCED Q51 Self-join: prev/next order per customer (and gap days). Q52 Self-join: detect 2+ same-day orders per customer. Q53 Self-join: "repeat-buyer pattern" - same product, same customer, > 30 days apart. Q54 Self-join: each ticket to the same customer's NEXT ticket. Q55 Self-join: inventory "shortage pair" - same product low-stock at two warehouses within 7 days. Q56 Self-join: customer signup -> first purchase delay (anchor + first event). Q57 Self-join: same-brand product pairs by price (cheaper vs pricier). Q58 Self-join: campaign overlap - two campaigns running same dates. Q59 Self-join: returns following purchases within 7 days. Q60 Self-join: customers with 2+ open tickets. Q61 Self-join: employee pairs working at the same store. Q62 Multi-join: product pairs in the same category. Q63 Self-join: employees at one store who joined within 30 days of each other. Q64 Self-join: multiple returns against the same order. Q65 Set-based: new customers per registration month (cumulative idea). Q66 Set-based: page-view path length per session. Q67 Aggregation: warehouses and how many products they track. Q68 Aggregation: suppliers and their shipment counts. Q69 Aggregation: headcount per role per store. Q70 Co-purchase self-join: customers who bought the same products as customer 1. Q71 Self-join: rank orders by value WITHIN each customer (before window functions). Q72 Use SELF JOIN to detect duplicate emails. Q73 Use SELF JOIN to detect ticket subject duplicates. Q74 Use SELF JOIN to detect inventory mismatches across warehouses. Q75 Use SELF JOIN to find "twin orders" - same cust, same amount, same day. SET OPS + RECONCILIATION Q76 FULL OUTER reconciliation: orders.cust_id vs customers.customer_id. Q77 FULL OUTER: products in inventory vs products ever sold - find drift. Q78 UNION ALL stacked: events from orders + tickets + reviews + calls. Q79 INTERSECT: customers in BOTH high-spend + active-reviewer cohorts. Q80 EXCEPT: customers who ordered but never reviewed. Q81 UNION ALL: "customer churn analysis" - combine multiple definitions of churn. Q82 UNION ALL + grand total (ROLLUP-like). Q83 INTERSECT: customers with a Delivered order AND a 2025 order. Q84 EXCEPT ALL: rows in old set but not new (with multiplicity). Q85 Set-op + CTE: differences between two computed reports. Q86 Full reconciliation report: 4-bucket layout (both / only-orders / only-reviews / neither). Q87 Multi-source dashboard: monthly revenue + ad cost in one UNION ALL output. Q88 UNION ALL + DENSE_RANK (preview Topic 16). Q89 Detect drift: customers with 2025 orders but none in 2024 (EXCEPT). Q90 Verify overlap: customers present in BOTH orders and payments (INTERSECT). Q91 Catch unmatched rows: customers who never placed an order (EXCEPT). Q92 PIVOT customers by tier using FILTER. Q93 UNPIVOT order item amount columns into rows. Q94 INTERSECT: customers who ordered from BOTH store 1 and store 2. Q95 INTERSECT three lifecycle stages. Q96 EXCEPT to find new-only campaigns vs last month. Q97 Build a "delta": customers (id <= 100) with no orders. Q98 Build a "diff": products in inventory but never sold. Q99 Combine LATERAL + UNION ALL: per customer, top 1 from each of 4 sources. Q100 Customer 360deg "all interactions" feed: UNION ALL across schemas, ordered by timestamp. Production scenarios, optimisation
RECURSIVE DEEP Q1 Employee hierarchy with level + path. Q2 Category tree (parent -> children). Q3 Reporting hierarchy: CEO + reports + sub-reports. Q4 Find depth of deepest sub-tree. Q5 Find longest path from any node to a leaf. Q6 Cycle detection with CYCLE clause (PG14+). Q7 BFS vs DFS in recursive CTE. Q8 Friend-of-friend at depth 3. Q9 Product dependency graph (bill of materials). Q10 Shortest path between two nodes (mini Dijkstra). Q11 Count of descendants per node. Q12 Roll-up totals through hierarchy. Q13 Sum of subtree per node. Q14 Order chain: refund -> original -> previous refund. Q15 Web session reconstruction. Q16 Date series via RECURSIVE (alternative to generate_series). Q17 Fibonacci sequence (toy demo). Q18 Recursive split: explode comma-separated list. Q19 Cycle in supplier graph. Q20 Cycle in friend graph. Q21 Detect orphaned nodes. Q22 Compute "depth from root" for every node. Q23 Mark all nodes within N hops of a starting node. Q24 Tree balance check. Q25 Build a "category breadcrumb" string for every product. LATERAL PRODUCTION Q26 Per customer, latest order + first order + total spend. Q27 Per customer, list 3 most-recent reviews + their products. Q28 Per ticket, top 3 comments by date. Q29 Per agent, count tickets by priority (via LATERAL). Q30 Per region, top 5 products by revenue. Q31 Per warehouse, latest snapshot of every product. Q32 Per courier, average delivery + last 5 shipments. Q33 Per supplier, sum shipped + last shipment date. Q34 Per campaign, attribution + spend + ROI in one row. Q35 Per platform, top 3 campaigns. Q36 Per category, top 3 products + their brand. Q37 Per dept, top earner + total payroll. Q38 Per store, employee with most tickets + avg salary. Q39 Per customer, page_views in last session. Q40 Per call_reason, longest call + its transcript. Q41 LATERAL explode JSONB array. Q42 LATERAL with generate_series for dates. Q43 LATERAL with subquery returning multiple cols. Q44 LATERAL with EXISTS short-circuit. Q45 Per customer, "next purchase" prediction (preview ML). Q46 Per product, "buyer pattern" (top 5 customers). Q47 Per region, "growth rate" via LATERAL on month series. Q48 Per store, "peak hour" detection. Q49 Chain LATERAL -> LATERAL -> LATERAL (3-level). Q50 LATERAL with aggregation per parent row. SET OPERATIONS PRODUCTION Q51 Customer interactions timeline (UNION ALL across 6 sources). Q52 Differences between two snapshots (EXCEPT both ways). Q53 INTERSECT high-value cohorts (3 definitions of "VIP"). Q54 UNION ALL with metric label for dashboards. Q55 UNION ALL across schemas. Q56 Cross-database UNION ALL via FDW. Q57 UNION ALL with GROUP BY + aggregation. Q58 UNION ALL with window function on result. Q59 UNION ALL of historical and current. Q60 UNION ALL of partitioned children explicitly. Q61 INTERSECT ALL preserving duplicates. Q62 EXCEPT ALL preserving duplicates. Q63 Combine LEFT JOIN + UNION ALL for "everyone but matches". Q64 Build "audit reconciliation" via FULL OUTER + COALESCE. Q65 Build "data drift" via EXCEPT both ways. Q66 Build "churn definition matrix" via INTERSECT. Q67 Build "lifecycle stage" via UNION ALL of stage queries. Q68 Build "attribution" via UNION ALL with weight. Q69 Build "customer interaction graph" via UNION ALL of edges. Q70 Build "product co-purchase" via SELF JOIN + UNION. Q71 Build "promotion overlap" via FULL OUTER. Q72 Build "tax audit" via UNION ALL with categorization. Q73 Build "refund audit" via UNION ALL. Q74 Combine set ops + window for ranking. Q75 Combine set ops + recursive for graph. MIXED MEGA-PATTERNS Q76 Customer activity stream -> first/last/most events. Q77 Product lifecycle: from launch to discontinue. Q78 Marketing funnel with multi-touch attribution. Q79 RFM + cohort + LATERAL "next purchase". Q80 RetailMart pulse: 50-metric exec dashboard. Q81 Inventory rebalancing recommendation. Q82 Supplier scorecard. Q83 Employee 360deg with ranking within dept. Q84 Customer journey reconstruction. Q85 Ad campaign ROI deep dive. Q86 Geo expansion plan: per-city stats + scoring. Q87 Loyalty program ROI. Q88 Returns analysis with root-cause flags. Q89 SLA breach root-cause analysis. Q90 Fraud detection report. Q91 Stockout risk forecast. Q92 Top 100 "at-risk" customers (composite score). Q93 Top 100 "growth" customers. Q94 Tier upgrade simulation. Q95 Pricing optimization preview. Q96 NPS deep dive by 5 dimensions. Q97 Churn deep dive (root causes). Q98 Cross-sell recommendations. Q99 Up-sell recommendations. Q100 Single mega-query: every interesting analytics result in 1 row per customer.