0Pricing
PostgreSQL Performance & Query Optimization · レッスン

LATERAL結合と相関参照の最適化

LATERAL結合によってサブクエリから先行するテーブルの列を参照する方法と、低速な相関サブクエリを効率的な行単位の参照に置き換える方法を学びます。

「LATERAL結合と相関参照の最適化」はCoddyKit上の無料PostgreSQL Performance & Query Optimizationレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPostgreSQL Performance & Query Optimization学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 PostgreSQL Performance & Query Optimizationコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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 true to keep unmatched outer rows
  • Back the inner filter and sort with a composite index
  • Confirm a Nested Loop + Index Scan in the plan

よくある質問

「LATERAL結合と相関参照の最適化」レッスンは無料ですか?

はい。「LATERAL結合と相関参照の最適化」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、PostgreSQL Performance & Query Optimizationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 PostgreSQL Performance & Query Optimizationコースには全4レッスンが含まれています。

「LATERAL結合と相関参照の最適化」で何を学びますか?

LATERAL結合によってサブクエリから先行するテーブルの列を参照する方法と、低速な相関サブクエリを効率的な行単位の参照に置き換える方法を学びます。 ブラウザで直接実行するハンズオンコードでPostgreSQL Performance & Query Optimizationを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

PostgreSQL Performance & Query Optimizationを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのPostgreSQL Performance & Query Optimizationは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「LATERAL結合と相関参照の最適化」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このPostgreSQL Performance & Query Optimizationレッスンでコードを書いて実行できますか?

はい。すべてのPostgreSQL Performance & Query Optimizationレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 結合アルゴリズムを理解する
  2. 複雑な結合の書き換え
  3. サブクエリ、CTE、結合の比較
  4. LATERAL結合と相関参照の最適化
← PostgreSQL Performance & Query Optimizationに戻る