πŸ€– AI/ML

Query Optimization

Query Optimization

A technique that improves performance by analyzing and optimizing the execution plans of database queries. Through index usage, join order adjustment, and execution plan analysis, it shortens query response time and minimizes system resource usage.

πŸ“– Detailed Explanation

Query Optimization is the process of finding the optimal execution plan when a SQL query runs in a database, in order to maximize performance. The database optimizer decides the execution plan automatically, but developers must properly manage query structure, index design, and statistics to get the best performance.

Query optimization is broadly divided into two approaches: (1) Rule-based Optimization (RBO) - decides the execution plan according to predefined rules, and (2) Cost-based Optimization (CBO) - calculates the cost of each execution plan based on table statistics and index information and selects the minimum-cost plan. Most modern RDBMSs (PostgreSQL, MySQL, Oracle, etc.) use CBO.

The key elements of optimization are index design, join optimization, and subquery handling. Proper indexes convert a Full Table Scan into an Index Seek, dramatically improving performance. Depending on the join order and method (Nested Loop, Hash Join, Merge Join), performance can differ by tens of times, and subqueries are often optimized by rewriting them as JOINs.

Query optimization is especially important in the AI/ML context. When extracting training data from large datasets, looking up real-time features from a Feature Store, or performing similarity search in a vector database, query performance directly affects the latency of the entire pipeline. Recently, AI-based query optimization (Learned Query Optimizer) is also being researched.

πŸ’» Code Example

We show the key query optimization techniques using PostgreSQL as the reference.

-- ============================================
-- Query Optimization μ‹€μ „ 예제 (PostgreSQL)
-- ============================================

-- 1. EXPLAIN ANALYZE둜 μ‹€ν–‰ κ³„νš 뢄석
-- -----------------------------------------
-- μ΅œμ ν™” μ „: Full Table Scan
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = 'test@example.com';
-- κ²°κ³Ό μ˜ˆμ‹œ: Seq Scan on users  (cost=0.00..25461.00 rows=1 width=123)
--           actual time=142.532..142.532 rows=1 loops=1

-- 인덱슀 생성
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);

-- μ΅œμ ν™” ν›„: Index Scan
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = 'test@example.com';
-- κ²°κ³Ό μ˜ˆμ‹œ: Index Scan using idx_users_email on users  (cost=0.42..8.44 rows=1 width=123)
--           actual time=0.028..0.029 rows=1 loops=1


-- 2. 볡합 인덱슀 섀계
-- -----------------------------------------
-- 자주 ν•¨κ»˜ μ‚¬μš©λ˜λŠ” 쑰건에 볡합 인덱슀 생성
-- μˆœμ„œ μ€‘μš”: 선택도(Selectivity)κ°€ 높은 μ»¬λŸΌμ„ μ•žμ—

-- WHERE status = 'active' AND created_at > '2024-01-01'
CREATE INDEX idx_orders_status_created
ON orders(status, created_at DESC);

-- Covering Index: 인덱슀만으둜 쿼리 처리 (Index Only Scan)
CREATE INDEX idx_orders_covering
ON orders(status, created_at)
INCLUDE (total_amount, user_id);

-- 이제 인덱슀만 읽고 ν…Œμ΄λΈ” μ ‘κ·Ό λΆˆν•„μš”
EXPLAIN ANALYZE
SELECT user_id, total_amount
FROM orders
WHERE status = 'completed' AND created_at > '2024-01-01';


-- 3. JOIN μ΅œμ ν™”
-- -----------------------------------------
-- μž‘μ€ ν…Œμ΄λΈ”μ„ λ¨Όμ € ν•„ν„°λ§ν•˜μ—¬ 쑰인

-- λΉ„νš¨μœ¨μ μΈ 쿼리
SELECT o.*, u.name
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.created_at > '2024-01-01'
  AND u.country = 'KR';

-- μ΅œμ ν™”: 필터링을 μ„œλΈŒμΏΌλ¦¬λ‘œ λ¨Όμ € μˆ˜ν–‰
SELECT o.*, u.name
FROM orders o
JOIN (
    SELECT id, name FROM users WHERE country = 'KR'
) u ON o.user_id = u.id
WHERE o.created_at > '2024-01-01';

-- λ˜λŠ” CTE ν™œμš© (가독성 ν–₯상)
WITH korean_users AS (
    SELECT id, name FROM users WHERE country = 'KR'
)
SELECT o.*, ku.name
FROM orders o
JOIN korean_users ku ON o.user_id = ku.id
WHERE o.created_at > '2024-01-01';


-- 4. μ„œλΈŒμΏΌλ¦¬λ₯Ό JOIN으둜 λ³€ν™˜
-- -----------------------------------------
-- λΉ„νš¨μœ¨μ : 상관 μ„œλΈŒμΏΌλ¦¬ (각 ν–‰λ§ˆλ‹€ μ„œλΈŒμΏΌλ¦¬ μ‹€ν–‰)
SELECT *
FROM products p
WHERE p.price > (
    SELECT AVG(price) FROM products WHERE category_id = p.category_id
);

-- μ΅œμ ν™”: JOIN으둜 λ³€ν™˜
SELECT p.*
FROM products p
JOIN (
    SELECT category_id, AVG(price) as avg_price
    FROM products
    GROUP BY category_id
) cat_avg ON p.category_id = cat_avg.category_id
WHERE p.price > cat_avg.avg_price;


-- 5. νŽ˜μ΄μ§€λ„€μ΄μ…˜ μ΅œμ ν™” (Keyset Pagination)
-- -----------------------------------------
-- λΉ„νš¨μœ¨μ : OFFSET은 큰 κ°’μ—μ„œ 느림
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 10000;

-- μ΅œμ ν™”: Keyset 방식 (μ»€μ„œ 기반)
-- 이전 νŽ˜μ΄μ§€μ˜ λ§ˆμ§€λ§‰ created_at 값을 μ‚¬μš©
SELECT * FROM posts
WHERE created_at < '2024-06-15 10:30:00'  -- λ§ˆμ§€λ§‰ ν•­λͺ©μ˜ timestamp
ORDER BY created_at DESC
LIMIT 20;


-- 6. 톡계 μ—…λ°μ΄νŠΈ
-- -----------------------------------------
-- λŒ€λŸ‰ 데이터 λ³€κ²½ ν›„ 톡계 κ°±μ‹  (μ˜΅ν‹°λ§ˆμ΄μ € 정확도 ν–₯상)
ANALYZE orders;
ANALYZE users;

-- νŠΉμ • 컬럼만 뢄석
ANALYZE orders(status, created_at);


-- 7. νŒŒν‹°μ…”λ‹ ν™œμš©
-- -----------------------------------------
-- λŒ€μš©λŸ‰ ν…Œμ΄λΈ”μ„ λ‚ μ§œλ³„λ‘œ νŒŒν‹°μ…”λ‹
CREATE TABLE events (
    id BIGSERIAL,
    event_type VARCHAR(50),
    payload JSONB,
    created_at TIMESTAMP NOT NULL
) PARTITION BY RANGE (created_at);

-- 월별 νŒŒν‹°μ…˜ 생성
CREATE TABLE events_2024_01 PARTITION OF events
    FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
CREATE TABLE events_2024_02 PARTITION OF events
    FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');

-- νŠΉμ • κΈ°κ°„ 쑰회 μ‹œ ν•΄λ‹Ή νŒŒν‹°μ…˜λ§Œ μŠ€μΊ” (Partition Pruning)
SELECT * FROM events
WHERE created_at >= '2024-01-15' AND created_at < '2024-01-20';


-- 8. 벑터 검색 μ΅œμ ν™” (pgvector)
-- -----------------------------------------
-- AI/MLμ—μ„œ 자주 μ‚¬μš©ν•˜λŠ” 벑터 μœ μ‚¬λ„ 검색
CREATE EXTENSION IF NOT EXISTS vector;

-- 벑터 μ»¬λŸΌμ— 인덱슀 생성 (IVFFlat 방식)
CREATE INDEX idx_embeddings_ivfflat
ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);  -- ν΄λŸ¬μŠ€ν„° 수 (데이터 크기에 따라 μ‘°μ •)

-- HNSW 인덱슀 (더 λΉ λ₯΄μ§€λ§Œ λ©”λͺ¨λ¦¬ 많이 μ‚¬μš©)
CREATE INDEX idx_embeddings_hnsw
ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

-- μœ μ‚¬λ„ 검색
SELECT id, content, embedding <=> '[0.1, 0.2, ...]'::vector AS distance
FROM documents
ORDER BY embedding <=> '[0.1, 0.2, ...]'::vector
LIMIT 10;

πŸ—£οΈ Say It Like This in Practice

In a meeting

"Looking at why this API's response time is slow, a Full Table Scan is occurring. Adding a composite index and verifying with EXPLAIN ANALYZE should fix it."

In a technical interview

"Query optimization starts with EXPLAIN analysis. Steer toward an Index Scan instead of a Seq Scan, optimize the join order and method, and, if needed, eliminate table access entirely with a Covering Index."

In a technical discussion

"For large-scale data processing, Keyset Pagination is more efficient than OFFSET. And with partitioning, you can use Partition Pruning to narrow the scan range even further."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌ "The more indexes you create, the better"

Indexes improve SELECT performance but degrade INSERT, UPDATE, and DELETE performance. They also take up storage space. Analyze actual query patterns and create only the necessary indexes, and periodically clean up unused indexes.

❌ "It's fine to fetch all columns with SELECT *"

Explicitly SELECTing only the columns you need reduces I/O and network transfer. In particular, using a Covering Index lets the query be handled by the index alone without table access, greatly improving performance.

βœ… The right approach

Always check the execution plan first with EXPLAIN ANALYZE. Compare the estimated cost with the actual time, and identify inefficient patterns such as Seq Scan and Nested Loop. After bulk data changes, refresh statistics with ANALYZE to keep the optimizer's judgments accurate.

πŸ”— Related Terms

πŸ“š Learn More