🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CTE Patterns: Lateral Joins, Apply, Unnest, Generate Series

Advanced SQLCTE Patterns⭐ Premium

Interview Question: "Explain the difference between LATERAL JOIN and CROSS APPLY. When would you use GENERATE_SERIES vs recursive CTE? How does UNNEST work with arrays?" — Asked at Amazon, Google, Netflix for Senior Data Engineer roles

â„šī¸

Difficulty: Advanced | Companies: Amazon, Google, Netflix, Uber, Stripe | Time: 45-60 minutes

Correlated subqueries in the FROM clause

A lateral join lets a subquery in the FROM clause reference columns of the tables already joined ahead of it, which turns "for each outer row, run this" into one statement instead of a cursor or an application loop. Everything below depends on evaluation order: the planner reads left to right, the lateral subquery may only look leftward, and it is re-executed once per qualifying outer row. That re-execution is both the power and the cost. A lateral top-two over three departments is trivial; over three million customers it is three million index scans, and the plan looks identical until you read the loops column. The pattern you choose decides whether the database performs one set-based pass or quietly performs the N+1 query you believed you had removed.

LATERAL Join Fundamentals

LATERAL allows subqueries to reference preceding FROM items:

-- Create sample data
CREATE TABLE departments (
    dept_id INT PRIMARY KEY,
    dept_name VARCHAR(100)
);

CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    name VARCHAR(100),
    dept_id INT,
    salary DECIMAL(12,2)
);

INSERT INTO departments VALUES
(1, 'Engineering'),
(2, 'Marketing'),
(3, 'Sales');

INSERT INTO employees VALUES
(1, 'Alice', 1, 120000),
(2, 'Bob', 1, 110000),
(3, 'Charlie', 1, 100000),
(4, 'Diana', 2, 95000),
(5, 'Eve', 2, 90000),
(6, 'Frank', 3, 85000),
(7, 'Grace', 3, 80000),
(8, 'Heidi', 3, 75000);

-- LATERAL: Get top 2 employees per department
SELECT 
    d.dept_name,
    e.name,
    e.salary
FROM departments d
CROSS JOIN LATERAL (
    SELECT name, salary
    FROM employees
    WHERE dept_id = d.dept_id
    ORDER BY salary DESC
    LIMIT 2
) e
ORDER BY d.dept_name, e.salary DESC;

-- LATERAL with array
SELECT 
    d.dept_name,
    e.top_employees
FROM departments d,
LATERAL (
    SELECT ARRAY_AGG(name ORDER BY salary DESC) AS top_employees
    FROM employees
    WHERE dept_id = d.dept_id
) e;

Output:

dept_namenamesalary
EngineeringAlice120000
EngineeringBob110000
MarketingDiana95000
MarketingEve90000
SalesFrank85000
SalesGrace80000

Read the plan before trusting a lateral. The correlated side should be an indexed lookup returning a handful of rows, and the outer side should be small enough that re-execution stays in the millisecond range. When the outer input is large, push a filter above the join: limiting departments to the four that reported activity this week removes far more work than any rewrite inside the subquery. Placement catches people out as well — the keyword makes the reference legal, but order still matters, so moving the referenced table to the right of the lateral fails with an unresolved column error rather than with a slow plan. Top-N, first-row, and pivot forms all reduce to one shape: order inside the subquery, limit inside the subquery, and the grouping key outside it.

CROSS APPLY (SQL Server)

-- SQL Server syntax (PostgreSQL uses LATERAL)
SELECT 
    d.dept_name,
    e.name,
    e.salary
FROM departments d
CROSS APPLY (
    SELECT TOP 2 name, salary
    FROM employees
    WHERE dept_id = d.dept_id
    ORDER BY salary DESC
) e;

-- OUTER APPLY (like LEFT JOIN LATERAL)
SELECT 
    d.dept_name,
    e.name,
    e.salary
FROM departments d
OUTER APPLY (
    SELECT TOP 1 name, salary
    FROM employees
    WHERE dept_id = d.dept_id
        AND salary > 100000
) e;

SQL Server names the same construct CROSS APPLY, with OUTER APPLY playing the role of a left join so unmatched outer rows still appear with nulls instead of vanishing. Portability is the practical concern: PostgreSQL, Oracle, and SQL Server accept the keyword in different positions, while MySQL supports neither and forces a correlated derived table or a loop in the application. When you migrate, search for APPLY and for comma joins that reference an earlier table — both compile to the same execution shape, and both break when someone simplifies the query by dropping the ordering inside the subquery. Leave a comment stating the intent, because a lateral top-N that silently degrades into a full sort after a refactor stays invisible until the latency graph moves.

UNNEST with Arrays

-- Create table with array column
CREATE TABLE user_preferences (
    user_id INT PRIMARY KEY,
    name VARCHAR(100),
    interests TEXT[],
    scores INT[]
);

INSERT INTO user_preferences VALUES
(1, 'Alice', ARRAY['hiking', 'reading', 'coding'], ARRAY[90, 85, 95]),
(2, 'Bob', ARRAY['gaming', 'cooking'], ARRAY[80, 70]),
(3, 'Charlie', ARRAY['travel', 'photography', 'music', 'sports'], ARRAY[88, 75, 92, 85]);

-- UNNEST array to rows
SELECT 
    name,
    UNNEST(interests) AS interest
FROM user_preferences
ORDER BY name, interest;

-- UNNEST with ordinality
SELECT 
    name,
    interest,
    position
FROM user_preferences,
LATERAL UNNEST(interests) WITH ORDINALITY AS t(interest, position)
ORDER BY name, position;

-- UNNEST multiple arrays simultaneously
SELECT 
    name,
    interest,
    score
FROM user_preferences,
LATERAL UNNEST(interests, scores) AS t(interest, score)
ORDER BY name, score DESC;

Output:

nameinterestscore
Alicecoding95
Alicehiking90
Alicereading85
Charliemusic92
Charlietravel88
Charliesports85
Charliephotography75
Bobgaming80
Bobcooking70

Expanding arrays is set-returning behaviour, and the two forms differ in ways that matter. A bare UNNEST in the select list expands in place alongside the other columns, while UNNEST ... WITH ORDINALITY in the FROM clause hands back the position, which is how you recover an ordering the array itself does not declare. Unnesting two arrays together pairs elements by position and pads the shorter with nulls, so unequal lengths produce silent misalignment instead of an error. The row multiplication deserves respect: the three users above yield nine rows because interests are three, two, and four, and a distinct count taken after expansion counts interests rather than users. Fold results back to the parent key before any measure is computed.

GENERATE_SERIES Patterns

-- Generate date series
SELECT 
    generate_series(
        '2024-01-01'::date,
        '2024-12-31'::date,
        '1 day'::interval
    )::date AS date_series;

-- Generate number series with step
SELECT 
    generate_series(1, 100, 5) AS number_series;

-- Fill gaps in time series
WITH date_series AS (
    SELECT generate_series(
        '2024-01-01'::date,
        '2024-01-10'::date,
        '1 day'::interval
    )::date AS sale_date
)
SELECT 
    ds.sale_date,
    COALESCE(s.amount, 0) AS amount
FROM date_series ds
LEFT JOIN sales s ON ds.sale_date = s.sale_date
ORDER BY ds.sale_date;

-- Generate hourly intervals
SELECT 
    generate_series(
        '2024-01-01 00:00:00'::timestamp,
        '2024-01-01 23:00:00'::timestamp,
        '1 hour'::interval
    ) AS hour_series;

Series generation is the other half of the toolkit: it fabricates the rows a table is missing, which is how gaps in a time series, calendar dimensions, and bucketed histograms get built without a scratch table. generate_series over dates needs an explicit step interval, and mixing a date bound with a timestamp step silently promotes the range — a boundary of the first of January with hourly steps stops at midnight rather than at the end of the day, truncating the last day of every report built on it. The gap-fill join is always a left join from the generated spine to the fact, with a COALESCE that states whether a missing row means zero or means unknown. Pick zero only when absence genuinely means the event did not happen.

Advanced CTE Patterns

-- Recursive CTE with LATERAL
WITH RECURSIVE org_chart AS (
    SELECT 
        emp_id,
        name,
        1 AS level,
        ARRAY[name] AS path
    FROM employees
    WHERE emp_id = 1
    
    UNION ALL
    
    SELECT 
        e.emp_id,
        e.name,
        oc.level + 1,
        oc.path || e.name
    FROM org_chart oc
    CROSS JOIN LATERAL (
        SELECT emp_id, name
        FROM employees
        WHERE manager_id = oc.emp_id
    ) e
    WHERE oc.level < 5
)
SELECT * FROM org_chart;

-- CTE with window functions
WITH ranked_employees AS (
    SELECT 
        dept_id,
        name,
        salary,
        RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rank
    FROM employees
)
SELECT 
    d.dept_name,
    r.name,
    r.salary,
    r.rank
FROM ranked_employees r
JOIN departments d ON r.dept_id = d.dept_id
WHERE r.rank <= 2
ORDER BY d.dept_name, r.rank;

Combining recursion with a lateral step is how you traverse a structure while keeping each level set-based: the recursive term fetches the children of the current frontier in one indexed lookup instead of joining the whole table again at every level. Two guardrails belong in every version, a level cap that fails loudly rather than a cycle that runs until the statement times out, and a visited key array so a loop in the data cannot multiply paths. The window-function variant that follows is a different animal — it ranks the whole set once and filters afterwards, which is far cheaper than per-group re-execution and is almost always the better answer when the requirement is a top-two ranking rather than a walk down a tree.

JSONB with LATERAL

-- Create table with JSONB
CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    customer_id INT,
    items JSONB
);

INSERT INTO orders (customer_id, items) VALUES
(1, '[{"product": "A", "qty": 2, "price": 10}, {"product": "B", "qty": 1, "price": 20}]'),
(2, '[{"product": "C", "qty": 3, "price": 15}]'),
(3, '[{"product": "A", "qty": 1, "price": 10}, {"product": "C", "qty": 2, "price": 15}]');

-- Unnest JSON array with LATERAL
SELECT 
    o.order_id,
    item->>'product' AS product,
    (item->>'qty')::int AS quantity,
    (item->>'price')::decimal AS price
FROM orders o,
LATERAL jsonb_array_elements(o.items) AS item
ORDER BY o.order_id;

-- Aggregate JSON items
SELECT 
    o.order_id,
    SUM((item->>'qty')::int * (item->>'price')::decimal) AS total
FROM orders o,
LATERAL jsonb_array_elements(o.items) AS item
GROUP BY o.order_id;

Shredding a JSON array with a lateral call to jsonb_array_elements is the set-based way to aggregate document contents: one row per element, grouped back to the order inside the same statement. The performance detail that matters is that the function runs per row, so without a GIN index or a generated column the entire orders table is parsed on every execution. When the same element field is filtered repeatedly, extract it once during the load into a real column, or index the expression so the planner can skip rows before parsing them. Also decide what happens to documents whose array is empty: they vanish from an inner-style expansion, which is correct for revenue lines and wrong for a completeness report that must show the zero.

Mathematical Properties

For a LATERAL join with outer rows and inner rows:

For GENERATE_SERIES with range and step :

â„šī¸

Performance Tip: LATERAL joins are powerful but can be expensive. Ensure the inner query is indexed and returns few rows per outer row.

Time Series Gap Filling

-- Create time series with gaps
CREATE TABLE metrics (
    metric_time TIMESTAMP,
    value DECIMAL(10,2)
);

INSERT INTO metrics VALUES
('2024-01-01 00:00:00', 100),
('2024-01-01 01:00:00', 110),
('2024-01-01 03:00:00', 95),  -- Gap at hour 2
('2024-01-01 05:00:00', 105); -- Gap at hour 4

-- Fill gaps with interpolation
WITH time_series AS (
    SELECT generate_series(
        '2024-01-01 00:00:00'::timestamp,
        '2024-01-01 05:00:00'::timestamp,
        '1 hour'::interval
    ) AS ts
)
SELECT 
    ts.ts AS metric_time,
    COALESCE(m.value, 
        LAG(m.value) OVER (ORDER BY ts.ts) + 
        (ts.ts - LAG(ts.ts) OVER (ORDER BY ts.ts))::interval / 
        (LEAD(ts.ts) OVER (ORDER BY ts.ts) - LAG(ts.ts) OVER (ORDER BY ts.ts))::interval *
        (LEAD(m.value) OVER (ORDER BY ts.ts) - LAG(m.value) OVER (ORDER BY ts.ts))
    ) AS interpolated_value
FROM time_series ts
LEFT JOIN metrics m ON ts.ts = m.metric_time
ORDER BY ts.ts;

âš ī¸

Common Pitfall: LATERAL with correlated subqueries can cause N+1 query problems. Always check execution plans.

Picking the right tool for the shape

Each pattern in this lesson answers a different structural question, so choose from the shape of the result you must produce rather than from the syntax you remember best.

Shape you must produceFirst choiceFallback when it is unavailable
Top N rows per outer groupLATERAL with ORDER BY and LIMITWindow function with a rank filter
Calendar or bucket spinegenerate_seriesRecursive CTE seeded from one row
One row per array elementUNNEST in the FROM clausejsonb_array_elements for documents
Missing intervals in a time seriesGenerated spine plus a left joinRecursive CTE stepping an interval
Tree traversal with a filter at each levelRecursive CTE with a lateral child lookupApplication loop with a depth cap

The fallback column is not a downgrade in every case. A window function ranks once for the whole set, so when the outer group list is itself large or unbounded, it beats re-executing a lateral per row. Conversely, when only a few outer rows qualify, the lateral scans less. Benchmark both with the real distribution of group sizes, because the answer flips depending on whether the table holds three departments or thirty thousand tenants.

Common Mistakes

Running a lateral subquery once per row over a large outer input

Fix: Filter the outer side first, or switch to a window function that ranks the whole set once

Taking a distinct count after expanding an array

Fix: Fold the expansion back to the parent key before any aggregate is computed

Generating a date spine with a date bound and an hourly step

Fix: Use a timestamp bound for hourly series so the final day is not truncated at midnight

Best Practices

  • Check the loops column in the plan for every correlated subquery you add
  • Keep ORDER BY and LIMIT inside the lateral subquery so the outer side sees only the rows it needs
  • Assert array lengths before pairing two UNNEST calls in one FROM clause
  • Write the missing-means-zero decision into the query with an explicit COALESCE
  • Comment the intent of each lateral so a later refactor does not silently change its cost

Interview Questions

Q1: LATERAL join or CROSS APPLY?

The same construct with different names and placement rules; PostgreSQL uses LATERAL before the subquery, SQL Server uses APPLY after the table list

Q2: When is generate_series better than a recursive CTE?

When the spine is uniform — fixed steps over a bounded range — because the planner materialises it without iterating the recursion

Q3: How does WITH ORDINALITY help?

It returns the position of each expanded element, which is how array order survives the trip into rows

Q4: What makes a lateral join expensive?

Re-execution: the inner query runs once per outer row, so cost scales with outer size unless the outer side is filtered first

Key Takeaways

  • Lateral subqueries may only reference tables to their left and execute once per outer row
  • Push filters above the join before optimizing anything inside the correlated subquery
  • UNNEST multiplies rows and pairs arrays positionally, so fold back to the parent key
  • generate_series fabricates the missing spine, and a left join plus COALESCE states what absence means
  • Choose between lateral and window ranking from the size of the outer group list, not from habit
🔒

Premium Content

CTE Patterns: Lateral Joins, Apply, Unnest, Generate Series

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement