데이터베이스
어려움
이론
SQL 쿼리 최적화
느린 쿼리를 분석하고 최적화하기
45분
90점
#3705
문제 설명
다음 느린 쿼리들을 분석하고 최적화하세요.
테이블 구조
orders (1000만 rows)
- id, user_id, product_id, quantity, price, status, created_at
users (100만 rows)
- id, name, email, created_at, country
products (10만 rows)
- id, name, category_id, price
order_items (5000만 rows)
- id, order_id, product_id, quantity, unit_price
최적화할 쿼리
-- Query 1: 최근 주문 조회 (매우 느림)
SELECT * FROM orders
WHERE status = "completed"
ORDER BY created_at DESC
LIMIT 100;
-- Query 2: 사용자별 총 주문액 (느림)
SELECT u.name, SUM(o.price) as total
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.created_at > "2024-01-01"
GROUP BY u.id;
-- Query 3: 카테고리별 매출 Top 10 (매우 느림)
SELECT p.category_id, SUM(oi.quantity * oi.unit_price) as revenue
FROM order_items oi
JOIN products p ON oi.product_id = p.id
JOIN orders o ON oi.order_id = o.id
WHERE o.created_at BETWEEN "2024-01-01" AND "2024-12-31"
GROUP BY p.category_id
ORDER BY revenue DESC
LIMIT 10;
제출 내용
- 각 쿼리의 문제점 분석
- 필요한 인덱스 설계
- 최적화된 쿼리
- 예상 성능 개선율