플래너가 행 수를 추정하는 방식
pg_statistic의 선택도 추정부터 계획 선택을 좌우하는 카디널리티까지 추적하는 방법을 배웁니다.
플래너가 행 수를 추정하는 방식은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 PostgreSQL Performance & Query Optimization 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Row Estimates Drive Everything
Before PostgreSQL executes a query, the planner must decide how to run it: sequential scan vs. index scan, nested loop vs. hash join, which table to drive a join from. Every one of these decisions hinges on a single guess: how many rows will each step produce?
- If the planner thinks a filter returns 5 rows, an index scan + nested loop looks cheap.
- If it thinks the same filter returns 5 million rows, a sequential scan + hash join wins.
These row-count guesses are called cardinality estimates. When they are wrong, the planner picks a bad plan even though its cost model is perfectly sound. This lesson traces exactly where those numbers come from.
Reading Estimates from EXPLAIN
Every node in an EXPLAIN plan reports the planner's estimate. The rows= value is the estimated cardinality for that node. Run EXPLAIN ANALYZE to compare it against the real count.
(cost=… rows=120 …)is the estimate.(actual … rows=118 …)is the truth.
A large gap between estimated and actual rows is the single most common root cause of slow plans. Train your eye to scan for it first.
EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE status = 'shipped'
AND country = 'DE';Where the Numbers Live: pg_statistic
The planner does not look at your data at plan time. It reads pre-computed summaries from the system catalog pg_statistic, populated by ANALYZE (run automatically by autovacuum). The human-readable view over it is pg_stats.
For each column, pg_stats exposes the building blocks of estimation:
null_frac— fraction of NULLs.n_distinct— number of distinct values.most_common_vals/most_common_freqs— the MCV list.histogram_bounds— buckets for the non-MCV remainder.
SELECT attname, null_frac, n_distinct,
most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'orders'
AND attname = 'status';Selectivity: The Core Fraction
Selectivity is the fraction of rows a predicate is estimated to keep, between 0 and 1. The estimated row count is simply:
estimated_rows = selectivity × total_rows
where total_rows comes from pg_class.reltuples (also refreshed by ANALYZE). So estimation reduces to two questions: what is the table's row count, and what fraction survives each predicate? Everything else is detail about how that fraction is computed.
SELECT relname, reltuples::bigint AS est_rows, relpages
FROM pg_class
WHERE relname = 'orders';Equality on a Common Value: the MCV List
For column = 'value', the planner first checks the most_common_vals (MCV) list. If the value is there, it uses the exact frequency from most_common_freqs — no math, just a lookup.
Example: if most_common_vals = {shipped, pending, cancelled} and most_common_freqs = {0.62, 0.25, 0.08}, then status = 'shipped' has selectivity 0.62. On a 1,000,000-row table that estimates 620,000 rows.
MCVs make skewed distributions estimate accurately — the planner knows exactly how popular the hot values are.
-- shipped is an MCV: selectivity = its stored frequency
SELECT most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';Equality on a Rare Value: the Residual
If the value is not in the MCV list, the planner assumes all non-MCV values are equally likely. It computes the leftover probability mass and spreads it evenly:
residual = 1 − sum(most_common_freqs) − null_fracn_distinct_residual = n_distinct − count(MCVs)selectivity = residual / n_distinct_residual
This is why estimates for rare values can be poor when the long tail is itself skewed: the uniform assumption inside the residual breaks down. MCVs cover the head; the residual is a flat approximation of the tail.
Range Predicates: the Histogram
For inequalities like amount > 500 or created_at BETWEEN …, the planner uses histogram_bounds. These bounds divide the non-MCV values into buckets each holding roughly the same number of rows (equi-depth, not equi-width).
To estimate amount < X, it finds where X falls among the bounds and interpolates linearly within the containing bucket. With N buckets, each represents about 1/N of the non-MCV rows, so the planner counts whole buckets below X plus a fractional slice of the boundary bucket.
SELECT histogram_bounds
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'amount';Combining Predicates: the Independence Trap
With multiple AND conditions on different columns, PostgreSQL multiplies their selectivities, assuming the columns are statistically independent:
sel(A AND B) = sel(A) × sel(B)
If status = 'shipped' is 0.62 and country = 'DE' is 0.10, the planner estimates 0.062 of the table. But if shipped orders are mostly German, the real fraction could be 0.30 — a 5× underestimate. Correlated columns are where single-column stats fail and plans collapse.
EXPLAIN
SELECT * FROM orders
WHERE status = 'shipped' -- sel ≈ 0.62
AND country = 'DE'; -- sel ≈ 0.10 → planner guesses 0.062Fixing Correlation: Extended Statistics
When columns are correlated, create extended statistics with CREATE STATISTICS. The dependencies kind teaches the planner functional dependencies; mcv stores multi-column most-common-value combinations so AND predicates are estimated jointly instead of multiplied.
After creating the object you must run ANALYZE on the table to populate it. Then the planner reads the joint distribution and stops assuming independence for those columns.
CREATE STATISTICS orders_status_country (dependencies, mcv)
ON status, country
FROM orders;
ANALYZE orders;Joins: Propagating Cardinality
Join row counts build on the per-table estimates. For an equi-join, PostgreSQL estimates output rows roughly as:
rows ≈ (outer_rows × inner_rows) / max(n_distinct_outer, n_distinct_inner)
using the join key's n_distinct from each side. This is why a bad single-table estimate cascades: if the planner thinks a filtered side has 5 rows when it really has 50,000, every join above it inherits the error and may choose a nested loop that runs 50,000 times instead of a hash join.
EXPLAIN ANALYZE
SELECT c.name, o.amount
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.country = 'DE';Keeping Estimates Honest
Estimates are only as good as the statistics behind them. Practical levers:
- Run
ANALYZEafter bulk loads; let autovacuum keep stats fresh. - Raise resolution on skewed columns with
ALTER TABLE … ALTER COLUMN … SET STATISTICS n(larger MCV list and histogram). - Add
CREATE STATISTICSfor correlated column groups. - Compare
EXPLAIN ANALYZEestimated vs. actual rows to find the node where the guess first goes wrong.
You debug from the bottom of the plan up: the first node with a large estimate/actual gap is usually the real culprit.
ALTER TABLE orders ALTER COLUMN amount SET STATISTICS 500;
ANALYZE orders;Quick Check: Combining Selectivities
Apply the estimation rules to a concrete case.
Recap: From Catalog to Cardinality
You can now trace a row estimate end to end:
- ANALYZE fills
pg_statistic/pg_statsand setsreltuples. - Equality uses the MCV list when the value is common, otherwise the uniform residual over
n_distinct. - Ranges interpolate within equi-depth
histogram_bounds. - Multiple ANDs multiply selectivities, assuming independence — the main source of estimation error.
- Extended statistics (
dependencies,mcv) fix correlated columns. - Joins combine per-side estimates via join-key
n_distinct, so single-table errors cascade upward.
Selectivity × row count produces the cardinalities that drive scan, join, and order choices. Master this and EXPLAIN output stops being mysterious — it becomes a story you can read.
자주 묻는 질문
“플래너가 행 수를 추정하는 방식” 강의는 무료인가요?
네 — “플래너가 행 수를 추정하는 방식” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
“플래너가 행 수를 추정하는 방식”에서 뭘 배우나요?
pg_statistic의 선택도 추정부터 계획 선택을 좌우하는 카디널리티까지 추적하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
PostgreSQL Performance & Query Optimization을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 PostgreSQL Performance & Query Optimization은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“플래너가 행 수를 추정하는 방식” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 PostgreSQL Performance & Query Optimization 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 PostgreSQL Performance & Query Optimization 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 플래너가 행 수를 추정하는 방식
- 상관된 열을 위한 다변량 통계
- MCV 및 고유값 수 보정
- 실제 행 수와 추정치 검증