LATERAL joins
- Version
- 19
- Since
- 9.3
- Review
- Draft
Summary#
A LATERAL item in FROM may refer to columns of the items before it. It is evaluated for those rows, which suits queries such as the top few children of each parent.
Syntax#
SELECT column_list
FROM parent AS p
LEFT JOIN LATERAL (
SELECT column_list
FROM child AS c
WHERE c.parent_id = p.parent_id
ORDER BY sort_column
LIMIT row_count
) AS top ON true;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE authors (
author_id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TEMPORARY TABLE posts (
post_id integer PRIMARY KEY,
author_id integer NOT NULL REFERENCES authors,
title text NOT NULL,
views integer NOT NULL
);
INSERT INTO authors VALUES (1, 'Mira'), (2, 'Noor'), (3, 'Omar');
INSERT INTO posts VALUES
(1, 1, 'Locks', 120), (2, 1, 'Indexes', 450), (3, 1, 'Vacuum', 300),
(4, 2, 'Joins', 80);
-- The two most viewed posts of each author, including authors with none.
SELECT a.name, top.title, top.views
FROM authors AS a
LEFT JOIN LATERAL (
SELECT p.post_id, p.title, p.views
FROM posts AS p
WHERE p.author_id = a.author_id
ORDER BY p.views DESC, p.post_id
LIMIT 2
) AS top ON true
ORDER BY a.author_id, top.views DESC, top.post_id;
ROLLBACK;
Expected output#
name|title|views
Mira|Indexes|450
Mira|Vacuum|300
Noor|Joins|80
Omar|NULL|NULL
(4 rows)
Common mistakes#
CROSS JOIN LATERAL drops a left row when the subquery returns nothing. Use LEFT JOIN LATERAL ... ON true to keep it. Give the inner ORDER BY a unique tie-breaker so LIMIT picks the same rows when values tie. Use a separate outer ORDER BY for the final order.
Version applicability#
PostgreSQL 9.3 added LATERAL. Earlier versions reject the keyword; a window function ranked per parent is one alternative for top-n queries.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0