PostgreSQL Performance & Query Optimization · 강의

LATERAL 조인 및 상관 조회 최적화

LATERAL 조인을 사용하면 하위 쿼리가 앞선 테이블의 열을 참조할 수 있는 방식과, 느린 상관 하위 쿼리를 행별 효율적인 조회로 대체하는 방법을 배워 보세요.

레슨 4/413개 단계

LATERAL 조인 및 상관 조회 최적화은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
무료로 시작

AI 튜터와 함께 SQL을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
22
레슨
88

자주 묻는 질문

“LATERAL 조인 및 상관 조회 최적화” 강의는 무료인가요?

네 — “LATERAL 조인 및 상관 조회 최적화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.

“LATERAL 조인 및 상관 조회 최적화”에서 뭘 배우나요?

LATERAL 조인을 사용하면 하위 쿼리가 앞선 테이블의 열을 참조할 수 있는 방식과, 느린 상관 하위 쿼리를 행별 효율적인 조회로 대체하는 방법을 배워 보세요. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 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(으)로 돌아가기