← All notes

LATERAL joins in PostgreSQL

Answer: A LATERAL subquery in FROM can reference columns from items listed before it, so it runs once per row on its left. It is the standard way to get top-N per group or to call a set-returning function for each row.

Top 3 orders per customer

SELECT c.name, o.id, o.total
FROM customers c
CROSS JOIN LATERAL (
  SELECT id, total FROM orders
  WHERE orders.customer_id = c.id
  ORDER BY total DESC LIMIT 3
) o;

Functions

LATERAL can also precede a function-call FROM item, but in this case it is a noise word, because the function expression can refer to earlier FROM items in any case. (S2)

SELECT p.id, t.tag FROM posts p, unnest(p.tags) AS t(tag);

Join refresher

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 7.2. Table Expressions, PostgreSQL License; PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: SELECT, PostgreSQL License.

Cite this

Permanent ID: iil:note:3c90kcfs

iinventedlight. 2026. "LATERAL joins in PostgreSQL." iinventedlight Library, iil:note:3c90kcfs, version of 2026-11-04. https://iinventedlight.com/library/notes/postgres-lateral-joins/. License: CC-BY-4.0.

@misc{iil_note_3c90kcfs,
  author = {{iinventedlight}},
  title = {{LATERAL joins in PostgreSQL}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/postgres-lateral-joins/},
  note = {Permanent ID iil:note:3c90kcfs. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-lateral-joins.md.