AI Hints
Home›PostgreSQL Tutorial›Joins, LATERAL and FILTER
PostgreSQL · Lesson 26 of 120

LATERAL Joins

A subquery per row.

⏱ 2 min read▶ Video at 21:54🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

For each genre, show the two books we have most of in stock. A normal subquery can't see the outer row. A lateral subquery can, so it runs once per genre.

  • Each genre
  • Top 2 by stock
  • LATERAL

Top two books per genre

The outer query lists three genres. The lateral subquery uses g dot genre, finds that genre's books, and keeps the two with the most stock. Run it. Two books for each genre.

query.sqlsql
SELECT g.genre, b.title, b.stock
FROM (VALUES ('Mystery'), ('Cooking'), ('Fantasy')) AS g(genre)
CROSS JOIN LATERAL (
  SELECT title, stock FROM books
  WHERE books.genre = g.genre
  ORDER BY stock DESC
  LIMIT 2
) b;
Output
  genre  |        title         | stock
---------+----------------------+-------
 Mystery | The Silent Orchard   |    58
 Mystery | Murder at Mill Lane  |    34
 Cooking | One Pan Dinners      |    12
 Cooking | Spice Roads          |     2
 Fantasy | Crown of Ash         |    31
 Fantasy | Dragons of Ember Bay |    28
(6 rows)

When to use LATERAL

Use lateral for top N per group, for calling a function per row, or for reusing a calculation. Left join lateral on true keeps rows even when the subquery finds nothing.

keyvalue
Top N per groupLIMIT inside
Functionsper row
Reusecalculations
LEFT JOIN LATERALkeep empty ones

Summary

A lateral subquery runs once per outer row, and can use its columns. Next, smarter aggregates with filter.

Key takeaways
  • LATERAL
  • Per row
  • Top N
Next up: Aggregates and FILTER — count only some rows