🗄️ Databases

CTE

Common Table Expression

A temporary result set defined with the WITH clause. Improves the readability and reusability of complex queries and efficiently processes hierarchical data with recursive queries.

📖 Detailed Explanation

CTE (Common Table Expression) is a feature that uses the WITH clause of SQL to define a temporary named result set within a query. It defines a subquery before the query body so it can be reused, and it separates a complex query into logical units to improve readability.

Non-Recursive CTE

It separates an ordinary subquery into a WITH clause and gives it a name. It is useful when the same subquery is referenced multiple times.

Recursive CTE

A CTE that references itself, it is essential for processing hierarchical data (organization charts, folder structures, category trees). It consists of a base case (Base Case) and a recursive member (Recursive Member).

CTE vs Subquery vs Temporary Table

Characteristics CTE Subquery Temporary Table
Definition Location Before the query (WITH) Inside the query Separate CREATE
Reuse Multiple times within the query Only once During the session
Recursion Support O X X (manual implementation)
Index X X O
Optimization Optimizer decides Inlined Materialized

💻 Code Example

Basic CTE - Referenced Multiple Times
-- 월별 매출 집계를 CTE로 정의 WITH monthly_sales AS ( SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS total_sales, COUNT(*) AS order_count FROM orders WHERE order_date >= '2024-01-01' GROUP BY DATE_TRUNC('month', order_date) ) -- CTE를 여러 번 참조하여 분석 SELECT month, total_sales, order_count, AVG(total_sales) OVER () AS avg_monthly_sales, total_sales - LAG(total_sales) OVER (ORDER BY month) AS growth FROM monthly_sales ORDER BY month;
Multiple CTEs - Complex Analysis
WITH -- 1단계: 고객별 주문 집계 customer_orders AS ( SELECT customer_id, COUNT(*) AS total_orders, SUM(amount) AS total_spent FROM orders GROUP BY customer_id ), -- 2단계: 고객 세그먼트 분류 customer_segments AS ( SELECT customer_id, total_orders, total_spent, CASE WHEN total_spent >= 100000 THEN 'VIP' WHEN total_spent >= 50000 THEN 'Regular' ELSE 'Basic' END AS segment FROM customer_orders ), -- 3단계: 세그먼트별 통계 segment_stats AS ( SELECT segment, COUNT(*) AS customer_count, AVG(total_spent) AS avg_spent FROM customer_segments GROUP BY segment ) -- 최종 결과: 세그먼트별 고객 목록과 통계 SELECT c.customer_id, c.segment, c.total_spent, s.customer_count, s.avg_spent, c.total_spent - s.avg_spent AS diff_from_avg FROM customer_segments c JOIN segment_stats s ON c.segment = s.segment ORDER BY c.segment, c.total_spent DESC;
Recursive CTE - Organization Chart (Employee Hierarchy)
-- 직원 테이블 구조: id, name, manager_id WITH RECURSIVE org_tree AS ( -- 기준 멤버 (Base Case): 최상위 관리자 SELECT id, name, manager_id, 1 AS level, ARRAY[name] AS path, name AS full_path FROM employees WHERE manager_id IS NULL UNION ALL -- 재귀 멤버 (Recursive Member): 하위 직원 SELECT e.id, e.name, e.manager_id, o.level + 1, o.path || e.name, o.full_path || ' > ' || e.name FROM employees e JOIN org_tree o ON e.manager_id = o.id ) SELECT REPEAT(' ', level - 1) || name AS hierarchy, level, full_path FROM org_tree ORDER BY path;
Recursive CTE - Category Tree
-- 카테고리 무한 뎁스 조회 WITH RECURSIVE category_tree AS ( -- 루트 카테고리 SELECT id, name, parent_id, 0 AS depth, CAST(id AS VARCHAR(1000)) AS sort_path FROM categories WHERE parent_id IS NULL UNION ALL -- 하위 카테고리 SELECT c.id, c.name, c.parent_id, ct.depth + 1, ct.sort_path || '/' || CAST(c.id AS VARCHAR(1000)) FROM categories c JOIN category_tree ct ON c.parent_id = ct.id WHERE ct.depth < 10 -- 무한 루프 방지 ) SELECT REPEAT('├─ ', depth) || name AS tree_view, depth, id FROM category_tree ORDER BY sort_path;
Recursive CTE - Generating a Date Series
-- 연속된 날짜 시리즈 생성 (30일) WITH RECURSIVE date_series AS ( SELECT CURRENT_DATE - INTERVAL '29 days' AS date UNION ALL SELECT date + INTERVAL '1 day' FROM date_series WHERE date < CURRENT_DATE ) -- 날짜별 주문 집계 (주문 없는 날도 포함) SELECT d.date, COALESCE(COUNT(o.id), 0) AS order_count, COALESCE(SUM(o.amount), 0) AS total_amount FROM date_series d LEFT JOIN orders o ON DATE(o.order_date) = d.date GROUP BY d.date ORDER BY d.date;
Recursive CTE - BOM (Bill of Materials) Expansion
-- 제품 BOM 전개 (부품 구성표) WITH RECURSIVE bom_explosion AS ( -- 최상위 제품 SELECT product_id, component_id, quantity, 1 AS level, CAST(component_id AS VARCHAR(1000)) AS path FROM bill_of_materials WHERE product_id = 'PROD-001' UNION ALL -- 하위 부품 SELECT b.product_id, b.component_id, b.quantity * bom.quantity AS total_quantity, bom.level + 1, bom.path || ' > ' || b.component_id FROM bill_of_materials b JOIN bom_explosion bom ON b.product_id = bom.component_id WHERE bom.level < 10 ) SELECT REPEAT(' ', level - 1) || component_id AS component, quantity AS total_needed, path FROM bom_explosion ORDER BY path;

💬 Real-world conversation examples

Junior Developer
"The same subquery is repeated three times in this query. How can I clean it up?"
Senior developer
"Pull it out into a CTE. If you define it like WITH customer_stats AS (...) and reference it multiple times, readability improves and the optimizer optimizes it for you."
Backend developer
"I need to query a comment-and-reply structure with unlimited depth, but calling the DB multiple times in a loop is slow."
DBA
"Try a recursive CTE. With WITH RECURSIVE you can fetch the whole tree at once. But be sure to set a depth limit to prevent infinite loops."
Data Analyst
"This analysis query is 200 lines long, and it's hard to understand the logic. It's also hard to test."
Senior Analyst
"Break it into CTEs step by step. If you separate it like filtering → aggregation → transformation → join, you can check each step's result with SELECT * FROM cte_name."

⚠️ Cautions

⚠️ Recursive CTE Infinite Loop

Without a termination condition in a recursive CTE, an infinite loop occurs! You must specify the termination condition with a WHERE clause and set a maximum depth limit using a depth or level column. The default limit is 100 iterations for PostgreSQL and 100 for SQL Server.

⚠️ Performance Considerations

CTE behavior differs by database. Before PostgreSQL 12, CTEs were always materialized (Materialized), which can be inefficient with large volumes of data. In MySQL 8.0 and above, SQL Server, and Oracle, the optimizer decides whether to inline.

⚠️ Controlling CTE Materialization (PostgreSQL 12+)

You can explicitly control materialization with WITH cte AS MATERIALIZED (...) or AS NOT MATERIALIZED (...). For large volumes of data, be sure to check the execution plan with EXPLAIN.

🔗 Related Terms

📚 Learn More