Query Optimizer
Query Optimizer
Selects the optimal execution plan. Cost-based optimization.
Query Optimizer
Selects the optimal execution plan. Cost-based optimization.
The Query Optimizer is a core component of a database engine that determines the most efficient way to execute a SQL query. Among the multiple execution plans that produce the same result, it selects the plan with the lowest cost.
A cost-based optimizer (CBO) estimates the cost (I/O, CPU, memory) of each execution plan using statistics such as table size, index selectivity, and data distribution. If these statistics become outdated, it may choose a wrong plan, so regular statistics updates are important.
The optimizer performs various optimizations, including join order determination, index selection, join method determination (Nested Loop, Hash, Merge), and subquery transformation. As the number of possible execution plans grows exponentially with more complex queries, it uses heuristics to find a sufficiently good plan within a time limit.
-- 통계 정보 갱신 (옵티마이저에 최신 정보 제공)
-- MySQL
ANALYZE TABLE orders;
ANALYZE TABLE customers;
-- PostgreSQL
ANALYZE orders;
ANALYZE customers;
-- 옵티마이저가 선택한 실행 계획 확인
EXPLAIN (ANALYZE, COSTS, FORMAT TEXT)
SELECT c.name, COUNT(o.id) as order_count
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.order_date > '2024-01-01'
GROUP BY c.id, c.name;
-- 옵티마이저 힌트 사용 (MySQL)
SELECT /*+ JOIN_ORDER(c, o) INDEX(o idx_order_date) */
c.name, COUNT(o.id)
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.order_date > '2024-01-01'
GROUP BY c.id, c.name;
-- PostgreSQL 힌트 (pg_hint_plan 확장)
/*+ Leading(c o) IndexScan(o idx_order_date) */
SELECT c.name, COUNT(o.id)
FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE o.order_date > '2024-01-01'
GROUP BY c.id, c.name;
-- 옵티마이저 통계 확인
-- MySQL
SHOW TABLE STATUS LIKE 'orders';
SHOW INDEX FROM orders;
-- PostgreSQL 통계 확인
SELECT
tablename,
n_live_tup,
n_dead_tup,
last_analyze
FROM pg_stat_user_tables
WHERE tablename = 'orders';
-- 컬럼별 통계 분포 확인
SELECT * FROM pg_stats
WHERE tablename = 'orders' AND attname = 'order_date';
Backend developer: It's the same query, but it was fast yesterday and it's slow today.
DBA: The optimizer may have chosen a different execution plan. Have you compared the EXPLAIN output?
Backend developer: Yes, yesterday it was an index scan, but today it's a full scan.
DBA: It seems the data volume crossed a threshold and the optimizer judged that a full scan is more efficient. You can update the statistics or force the index with a hint.
Interviewer: How do you respond when the optimizer chooses a wrong execution plan?
Candidate: First, I update the statistics with ANALYZE. If that doesn't work, I use a hint, but since a hint can actually degrade performance when the data distribution changes, I use it as a last resort. Fundamentally, it's better to improve the query structure or the indexes.
Interviewer: What are the limitations of a cost-based optimizer?
Candidate: When the statistics become outdated, it makes wrong estimates, and with complex queries it cannot examine all the plans. Also, it is difficult to accurately estimate the cost of correlated subqueries or function calls.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Senior: This query has a hardcoded hint. Why did you put it in?
Junior: Because the optimizer chose a slow plan.
Senior: A hint is a temporary fix. If the data grows tenfold, this hint can actually become poison. Check the statistics update cycle, and if possible, solve it by improving the indexes or the query structure.