LATERAL Joins
A LATERAL join in SQL is a join to a subquery that can refer to columns of the tables written before it, so the subquery runs once for each of their rows. It is used for "for each row, find these related rows" questions where the inner query needs its own ORDER BY and LIMIT, such as each student's latest two payments. An ordinary subquery in FROM can't see the other tables in the same FROM; LATERAL lifts that restriction. In this lesson, we will learn the syntax, keep rows with no matches using LEFT JOIN LATERAL, compare LATERAL with window functions, and see SQL Server's CROSS APPLY and OUTER APPLY.
In One Minute
FROM a CROSS JOIN LATERAL (SELECT ... WHERE x = a.col ...) AS bruns the subquery per row ofa.- Without
LATERAL, the subquery can't refer toa; PostgreSQL reportsinvalid reference to FROM-clause entry. CROSS JOIN LATERALdrops rows ofawhose subquery returns nothing;LEFT JOIN LATERAL ... ON truekeeps them.- It's ideal for top N per row:
ORDER BY ... LIMIT ninside the subquery. - SQL Server and Oracle call it
CROSS APPLYandOUTER APPLY.
Syntax
SELECT ...
FROM outer_table AS o
CROSS JOIN LATERAL (
SELECT ... FROM other_table WHERE other_table.key = o.key ORDER BY ... LIMIT n
) AS sub;
-- keep outer rows with no matches:
LEFT JOIN LATERAL ( ... ) AS sub ON trueWhy LATERAL Is Needed
A plain subquery in FROM is computed on its own, so it can't use a column from another table in the same FROM:
SELECT s.first_name, p.payment_id
FROM students AS s
JOIN (SELECT payment_id, student_id
FROM payments
WHERE payments.student_id = s.student_id
LIMIT 2) AS p ON true;ERROR: invalid reference to FROM-clause entry for table "s"
DETAIL: There is an entry for table "s", but it cannot be referenced from this part of the query.
HINT: To reference that table, you must mark this subquery with LATERAL.Explanation: The hint says exactly what to do: mark the subquery with LATERAL. With it, the subquery is evaluated separately for each student, and s.student_id refers to the current student.
Example: Each Student's Latest Two Payments
SELECT s.first_name, p.payment_id, p.paid_on, p.amount_usd
FROM students AS s
CROSS JOIN LATERAL (
SELECT payment_id, paid_on, amount_usd
FROM payments
WHERE payments.student_id = s.student_id
ORDER BY paid_on DESC
LIMIT 2
) AS p
ORDER BY s.student_id, p.paid_on DESC; first_name | payment_id | paid_on | amount_usd
------------+------------+------------+------------
Srihitha | 5 | 2026-01-05 | 200.00
Srihitha | 4 | 2025-12-29 | 550.00
Navika | 7 | 2025-12-19 | 225.00
Navika | 6 | 2025-11-14 | 225.00
(4 rows)Explanation: For Srihitha, the subquery returns her two latest payments; for Navika, hers. Advitha has no payments, so her subquery returns no rows, and CROSS JOIN drops her, like an inner join.
LEFT JOIN LATERAL: Keeping Every Row
LEFT JOIN LATERAL (...) ON true keeps the outer row even when the subquery returns nothing, with NULL in its columns:
SELECT s.first_name, p.payment_id, p.paid_on, p.amount_usd
FROM students AS s
LEFT JOIN LATERAL (
SELECT payment_id, paid_on, amount_usd
FROM payments
WHERE payments.student_id = s.student_id
ORDER BY paid_on DESC
LIMIT 2
) AS p ON true
ORDER BY s.student_id, p.paid_on DESC; first_name | payment_id | paid_on | amount_usd
------------+------------+------------+------------
Srihitha | 5 | 2026-01-05 | 200.00
Srihitha | 4 | 2025-12-29 | 550.00
Advitha | NULL | NULL | NULL
Navika | 7 | 2025-12-19 | 225.00
Navika | 6 | 2025-11-14 | 225.00
(5 rows)Explanation: Advitha now appears once, with NULLs. ON true is needed because LEFT JOIN requires an ON clause; the real matching condition is already inside the subquery.
LATERAL vs Window Functions
The same "top N per group" can be written with ROW_NUMBER, as in Ranking Functions:
| Approach | How it works | Good when |
|---|---|---|
ROW_NUMBER() in a CTE, then rn <= 2 | Numbers all rows, then filters | You need most rows anyway, or no index helps |
LATERAL (... ORDER BY ... LIMIT 2) | Runs a small query per outer row | Few outer rows, an index on (key, order column), or several columns from the inner query |
With an index on payments (student_id, paid_on), each lateral subquery can read exactly two index entries, which is very fast for a few students and many payments. LATERAL can also compute several values per row at once:
SELECT c.title, x.students, x.paid
FROM courses AS c
CROSS JOIN LATERAL (
SELECT count(DISTINCT e.student_id) AS students,
coalesce(sum(p.amount_usd), 0) AS paid
FROM enrollments AS e
LEFT JOIN payments AS p
ON p.student_id = e.student_id AND p.course_id = e.course_id
WHERE e.course_id = c.course_id
) AS x
ORDER BY c.course_id; title | students | paid
-------------------+----------+--------
Java Basics | 2 | 450.00
Java OOP | 1 | 500.00
Java Collections | 1 | 550.00
SQL Basics | 2 | 200.00
JavaScript Basics | 1 | 450.00
Git Basics | 0 | 0
(6 rows)Explanation: For each course, the lateral subquery counts its students and totals their payments in one pass. An aggregate without GROUP BY always returns one row, so Git Basics is kept, with 0 students.
CROSS APPLY and OUTER APPLY
SQL Server and Oracle spell the same idea APPLY:
| PostgreSQL | SQL Server / Oracle |
|---|---|
CROSS JOIN LATERAL (...) AS p | CROSS APPLY (...) AS p |
LEFT JOIN LATERAL (...) AS p ON true | OUTER APPLY (...) AS p |
MySQL 8.0.14 and later support LATERAL too. Tabs showing each database's version are coming to this course.
Common Mistakes
Forgetting LATERAL. The subquery can't see the outer table, and PostgreSQL says so.
Losing rows with CROSS JOIN LATERAL. Use LEFT JOIN LATERAL ... ON true to keep outer rows with no matches.
No ORDER BY with LIMIT. "Latest two" needs ORDER BY paid_on DESC; without it, LIMIT picks arbitrary rows.
Using LATERAL for a single value. A scalar subquery or a join is simpler.
Interview Corner
What does LATERAL do?
It lets a subquery in FROM refer to columns of tables listed before it, so the subquery is evaluated once per row of those tables.
How do you get the top 3 orders per customer with LATERAL?
FROM customers c CROSS JOIN LATERAL (SELECT ... FROM orders o WHERE o.customer_id = c.id ORDER BY o.created_at DESC LIMIT 3) x, or LEFT JOIN LATERAL ... ON true to keep customers without orders.
What's the SQL Server equivalent of LATERAL?
CROSS APPLY for CROSS JOIN LATERAL, and OUTER APPLY for LEFT JOIN LATERAL ... ON true.
Practice
Challenge (chapter checkpoint): Build a monthly report: for every payment, show the month (to_char(date_trunc('month', paid_on), 'YYYY-MM')), payment_id, student_id, the amount, the running total within that month (in date order), and the payment's rank by amount within the month, largest first. Sort by month, then date.
Show solution
SELECT to_char(date_trunc('month', paid_on), 'YYYY-MM') AS month,
payment_id, student_id, amount_usd,
sum(amount_usd) OVER (PARTITION BY date_trunc('month', paid_on)
ORDER BY paid_on, payment_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS month_running_total,
RANK() OVER (PARTITION BY date_trunc('month', paid_on)
ORDER BY amount_usd DESC) AS rank_in_month
FROM payments
ORDER BY month, paid_on, payment_id; month | payment_id | student_id | amount_usd | month_running_total | rank_in_month
---------+------------+------------+------------+---------------------+---------------
2025-08 | 1 | 101 | 450.00 | 450.00 | 1
2025-10 | 2 | 101 | 250.00 | 250.00 | 1
2025-11 | 6 | 103 | 225.00 | 225.00 | 1
2025-12 | 3 | 101 | 250.00 | 250.00 | 2
2025-12 | 7 | 103 | 225.00 | 475.00 | 3
2025-12 | 4 | 101 | 550.00 | 1025.00 | 1
2026-01 | 5 | 101 | 200.00 | 200.00 | 1
(7 rows)December, the busiest month, shows the pieces working together: its running total climbs 250.00, 475.00, 1,025.00, and the $550.00 payment ranks first even though it came last. Every other month has one payment, ranked 1, with a running total equal to its amount.
Key Takeaways
| You want to | Write |
|---|---|
| Top 2 per student | CROSS JOIN LATERAL (SELECT ... WHERE p.student_id = s.student_id ORDER BY paid_on DESC LIMIT 2) AS p |
| Keep students with none | LEFT JOIN LATERAL (...) AS p ON true |
| SQL Server | CROSS APPLY (...), OUTER APPLY (...) |
Was this tutorial helpful?