Cookbook recipe

Eliminate N+1 queries with LATERAL joins

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source
Estimated investigation4 min

Scenario

Your app runs one query per parent row to fetch its latest child. A LATERAL join does it in a single round trip. Diagnose it Fetch the top child per parent in one query: SELECT u.id,…

Investigation Path

Your app runs one query per parent row to fetch its latest child. A LATERAL join does it in a single round trip.

Diagnose it

Fetch the top child per parent in one query:

SELECT u.id, last_order.*
FROM users u
CROSS JOIN LATERAL (
  SELECT * FROM orders o
  WHERE o.user_id = u.id
  ORDER BY o.created_at DESC
  LIMIT 1
) AS last_order;

Why it happens

N+1 patterns send a query per row from the application, adding network and planning overhead per call. LATERAL lets a subquery reference the outer row so the database does the per-row lookup set-based.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • How to fix it
  • Prevent it next time
  • Related & next steps
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Career Impact

This scenario builds production judgment and operational confidence under pressure.

Open Career Dashboard →

Keep going

Related & next steps

Was this helpful?

← All cookbook recipes