2.3 Estimate 오류 찾기
Planner가 잘못된 plan을 고르는 흔한 출발점은 row estimate 오류입니다. 각 node의 estimated rows와 actual rows를 비율로 비교합니다.
estimate factor = max(actual / estimated, estimated / actual)
0으로 추정된 값은 별도로 다룹니다. Tree 아래쪽의 큰 오류가 join과 aggregate 위로 증폭되는지 찾습니다.
원인 후보
ANALYZE가 오래됐거나 sample이 부족함- Data가 특정 값에 치우침
- 두 column이 상관되지만 독립으로 추정됨
- Expression과 function 결과 통계가 없음
- Parameterized query에서 generic plan 사용
- Join key의 분포와 uniqueness를 잘못 가정
SELECT relname, last_analyze, last_autoanalyze,
n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE relname IN ('orders', 'customers');
Estimate 오류를 발견했다고 cost parameter를 먼저 조정하지 않습니다. Statistics freshness, target, extended statistics, query predicate를 먼저 검토합니다.
Plan은 PostgreSQL release와 data 변화로 달라질 수 있습니다. 개선 전후 plan을 JSON으로 보존하면 자동 비교하기 좋습니다.
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT ...;