Ottimizzare i join LATERAL e le ricerche correlate
Impari come i join LATERAL permettono a una sottoquery di fare riferimento alle colonne delle tabelle precedenti e come usarli per sostituire sottoquery correlate lente con ricerche efficienti riga per riga.
Ottimizzare i join LATERAL e le ricerche correlate è una lezione PostgreSQL Performance & Query Optimization gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento PostgreSQL Performance & Query Optimization, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Impara SQL con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 22
- Lezioni
- 88
Domande Frequenti
La lezione «Ottimizzare i join LATERAL e le ricerche correlate» è gratuita?
Sì — il testo completo di «Ottimizzare i join LATERAL e le ricerche correlate» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso PostgreSQL Performance & Query Optimization, passa a CoddyKit PRO. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.
Cosa imparerò in «Ottimizzare i join LATERAL e le ricerche correlate»?
Impari come i join LATERAL permettono a una sottoquery di fare riferimento alle colonne delle tabelle precedenti e come usarli per sostituire sottoquery correlate lente con ricerche efficienti riga p… Eserciti PostgreSQL Performance & Query Optimization con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare PostgreSQL Performance & Query Optimization?
Non è richiesta alcuna esperienza precedente. PostgreSQL Performance & Query Optimization su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Ottimizzare i join LATERAL e le ricerche correlate»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione PostgreSQL Performance & Query Optimization?
Sì. Ogni lezione PostgreSQL Performance & Query Optimization include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Comprendere gli algoritmi di join
- Riscrittura di join complessi
- Sottoquery, CTE e join a confronto
- Ottimizzare i join LATERAL e le ricerche correlate