LATERAL-Joins und korrelierte Zugriffe optimieren
Lernen Sie, wie LATERAL-Joins einer Unterabfrage den Zugriff auf Spalten früherer Tabellen ermöglichen und wie Sie damit langsame korrelierte Unterabfragen durch effiziente zeilenweise Zugriffe ersetzen.
LATERAL-Joins und korrelierte Zugriffe optimieren ist eine kostenlose PostgreSQL Performance & Query Optimization-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des PostgreSQL Performance & Query Optimization-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der PostgreSQL Performance & Query Optimization-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
What is a LATERAL Join?
A LATERAL join lets a subquery in the FROM clause reference columns from tables listed before it. Without LATERAL, a subquery in FROM cannot see the outer rows.
The Problem It Solves
Suppose you want, for each customer, their three most recent orders. A plain join cannot easily limit rows per customer. LATERAL evaluates the subquery once per outer row, so a per-row LIMIT works.
Basic Syntax
Place LATERAL before the subquery and reference the outer table inside it.
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 created_at DESC
LIMIT 3
) o;LEFT JOIN LATERAL
Use LEFT JOIN LATERAL ... ON true when you still want outer rows that have no matching subquery results, such as customers with no orders.
SELECT c.name, o.id
FROM customers c
LEFT JOIN LATERAL (
SELECT id FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC LIMIT 1
) o ON true;LATERAL vs Correlated Subquery
A correlated subquery in the SELECT list can only return one column per row. LATERAL can return multiple columns and multiple rows, making it far more flexible.
Indexing for LATERAL
Because the subquery runs once per outer row, the inner filter and sort must be index-backed. Create a composite index matching the WHERE and ORDER BY columns.
CREATE INDEX idx_orders_cust_created
ON orders (customer_id, created_at DESC);Reading the Plan
A well-optimized LATERAL shows a Nested Loop with an Index Scan on the inner side. If you see a Seq Scan inside the loop, the supporting index is missing.
EXPLAIN ANALYZE
SELECT c.name, o.id
FROM customers c
CROSS JOIN LATERAL (
SELECT id FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC LIMIT 3
) o;LATERAL with Set-Returning Functions
LATERAL also works with functions like unnest or jsonb_array_elements, expanding array columns per row.
SELECT p.id, tag
FROM products p
CROSS JOIN LATERAL unnest(p.tags) AS tag;Top-N Per Group Pattern
The most common use of LATERAL is the top-N-per-group query. It is usually faster than window-function approaches when N is small and an index supports the order.
When to Avoid LATERAL
If the outer table is huge and the inner subquery has no supporting index, running it millions of times is slow. In that case a window function or a single aggregated join may win. Always measure both.
Passing Computed Values Forward
LATERAL can also compute an intermediate value and reuse it in later expressions, avoiding repeating the same calculation. Each LATERAL block sees the columns produced before it.
SELECT o.id, m.margin
FROM orders o
CROSS JOIN LATERAL (
SELECT o.total - o.cost AS margin
) m
WHERE m.margin > 0;Quick Check
Test your LATERAL knowledge.
Recap
You learned LATERAL joins:
- They let a FROM-clause subquery see earlier tables' columns
- Perfect for top-N-per-group and per-row lookups
- Use
LEFT JOIN LATERAL ... ON trueto keep unmatched outer rows - Back the inner filter and sort with a composite index
- Confirm a Nested Loop + Index Scan in the plan
Häufig gestellte Fragen
Ist die Lektion „LATERAL-Joins und korrelierte Zugriffe optimieren“ kostenlos?
Ja — der vollständige Text von „LATERAL-Joins und korrelierte Zugriffe optimieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des PostgreSQL Performance & Query Optimization-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der PostgreSQL Performance & Query Optimization-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „LATERAL-Joins und korrelierte Zugriffe optimieren“?
Lernen Sie, wie LATERAL-Joins einer Unterabfrage den Zugriff auf Spalten früherer Tabellen ermöglichen und wie Sie damit langsame korrelierte Unterabfragen durch effiziente zeilenweise Zugriffe erset… Du übst PostgreSQL Performance & Query Optimization mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um PostgreSQL Performance & Query Optimization zu starten?
Keine Vorkenntnisse erforderlich. PostgreSQL Performance & Query Optimization auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „LATERAL-Joins und korrelierte Zugriffe optimieren“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser PostgreSQL Performance & Query Optimization-Lektion Code schreiben und ausführen?
Ja. Jede PostgreSQL Performance & Query Optimization-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Join-Algorithmen verstehen
- Komplexe Joins umschreiben
- Subqueries vs. CTEs vs. Joins
- LATERAL-Joins und korrelierte Zugriffe optimieren