Appearance
Advanced Statistics & Histogram Tuning
HOT Chain Length Limits & Detection
HOT (Heap-Only Tuples) updates are one of PostgreSQL's most underutilized optimization features, but they fail silently: when an UPDATE cannot be HOT (an indexed column changed, or the page is full), every update writes new entries into all indexes, which causes index bloat and write amplification.
What Are HOT Updates? A HOT update needs two conditions: the UPDATE changes no column referenced by an index (summarizing indexes excepted), AND the page holding the old row has enough free space for the new version. Then PostgreSQL keeps the existing index entries and chains the new heap tuple on the same page, which saves index maintenance overhead.
sql
-- PostgreSQL 18
-- Frequently updated table (the row count in a real system is illustrative)
DROP TABLE IF EXISTS users CASCADE;
CREATE TABLE users (
id BIGINT PRIMARY KEY,
name VARCHAR(100), -- rarely updated
email VARCHAR(100), -- rarely updated
login_count INT DEFAULT 0, -- FREQUENTLY updated
last_login TIMESTAMP, -- FREQUENTLY updated
status VARCHAR(20) DEFAULT 'active' -- FREQUENTLY updated, but indexed below
);
CREATE INDEX idx_email ON users (email);
CREATE INDEX idx_status ON users (status);
-- Load 100,000 rows so the examples below have data to measure
INSERT INTO users (id, name, email) SELECT g, 'n' || g, 'e' || g FROM generate_series(1, 100000) g;
-- HOT-eligible: no indexed column changes (it still needs free space on the page)
UPDATE users SET login_count = login_count + 1, last_login = NOW()
WHERE id = 12345;
-- Not HOT: status is indexed, so a new entry is added to idx_status
UPDATE users SET status = 'inactive'
WHERE id = 12345;The Silent Failure: Updates That Are Not HOT
HOT chains stay inside one heap page and are pruned during normal operation (docs: "row versions other than the oldest and the newest can be completely removed during normal operation"), so long chains are not the usual problem. The usual silent failure is the opposite: updates that are NOT HOT because the page is full (default fillfactor is 100) or an indexed column changed. Each such update writes new entries into every index of the table, bloating the indexes and increasing WAL volume. Watch the HOT ratio (n_tup_hot_upd / n_tup_upd), not chain length.
Measured on PostgreSQL 18 (100,000-row users table, 50,000 UPDATEs of login_count/last_login, indexes only on email and status): fillfactor 100 gave 0% HOT updates, fillfactor 75 gave 30% HOT. Your numbers will differ; measure on your own workload.
Detection Query:
sql
-- PostgreSQL 18
-- Cheap check first: HOT ratio and dead tuples from the statistics views
SELECT relname, n_tup_upd, n_tup_hot_upd,
ROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 1) AS hot_pct,
n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'users';
-- Page-level detail. pgstattuple() always scans the WHOLE table (heavy I/O on big tables);
-- pgstattuple_approx() skips all-visible pages, so prefer it on production tables.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len / 8192 AS total_blocks,
approx_tuple_percent, dead_tuple_percent, approx_free_percent
FROM pgstattuple_approx('users');text
-- Measured result (100,000 rows loaded above, run after the 50,000-row UPDATE of the fillfactor comparison below; values change with data).
-- Run right after the load and before that UPDATE you instead see hot_pct NULL, dead_tuple_percent about 0 and total_blocks 824:
-- hot_pct 0.0 | dead_tuple_percent 29.55 | approx_free_percent 0.38 | total_blocks 1450
-- Reading it: low hot_pct on an update-heavy table + dead tuples + almost no free space
-- on the pages = updates cannot stay on the page, so they are not HOT.Find Vulnerable Tables Across Entire Database:
sql
SELECT
schemaname,
relname,
n_tup_hot_upd AS hot_count,
n_tup_upd AS total_updates,
ROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 2) AS hot_ratio_percent
FROM pg_stat_user_tables
WHERE n_tup_upd > 1000000
ORDER BY hot_count DESC;
-- High HOT ratio (n_tup_hot_upd / n_tup_upd) is GOOD (fewer index writes); a LOW ratio on update-heavy tables is the problem:
-- schemaname | relname | hot_count | total_updates | hot_ratio_percent
-- ----------+-----------+--------------+---------------+------------------
-- public | users | 4,500,000 | 25,000,000 | 18.0% (LOW)
-- public | sessions | 8,200,000 | 15,000,000 | 54.7%
-- public | orders | 3,400,000 | 5,000,000 | 68.0%Fix: fillfactor Tuning
Lower fillfactor leaves free space on each page so more updates qualify as HOT (docs: "You can increase the likelihood of sufficient page space for HOT updates by decreasing a table's fillfactor").
sql
-- PostgreSQL 18
-- Default fillfactor is 100: pages are packed full, so a page rarely has room for a HOT update.
-- Compare with fillfactor 75 (25% of each page reserved), same data, same updates:
DROP TABLE IF EXISTS users_ff75;
CREATE TABLE users_ff75 (LIKE users INCLUDING ALL) WITH (fillfactor = 75);
INSERT INTO users_ff75 SELECT * FROM users;
ANALYZE users;
ANALYZE users_ff75;
UPDATE users SET login_count = login_count + 1, last_login = NOW() WHERE id <= 50000;
UPDATE users_ff75 SET login_count = login_count + 1, last_login = NOW() WHERE id <= 50000;
SELECT pg_stat_force_next_flush();
SELECT relname, n_tup_upd, n_tup_hot_upd,
ROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables
WHERE relname IN ('users', 'users_ff75')
ORDER BY relname;text
-- Measured result (PostgreSQL 18, 100,000 rows loaded above; n_tup_upd and HOT counts are approximate and change with data):
-- relname | n_tup_upd | n_tup_hot_upd | hot_pct
-- users | 50000 | 0 | 0.0
-- users_ff75 | 50000 | 15003 | 30.0On an existing table, ALTER TABLE users SET (fillfactor = 75) only affects pages written afterwards. Rewriting old pages needs VACUUM FULL (ACCESS EXCLUSIVE lock, blocks all reads and writes: maintenance window only) or an online rewrite with pg_repack. Cost of a lower fillfactor: the table is about 1/0.75 larger, so more I/O for scans. Counters are cumulative: compare the ratio over the same time window before and after. Do not expect a fixed speed-up; measure with EXPLAIN (ANALYZE, BUFFERS) before and after.
Statistics Histogram Analysis
PostgreSQL stores histogram of values for each column in pg_statistic. Understanding this is crucial for query optimization.
What's Stored in Statistics?
The sections below share one fixture table, orders (skewed status and product_id; city determines country):
sql
-- PostgreSQL 18
CREATE TABLE orders (
id bigserial PRIMARY KEY, user_id int, product_id int, status text, priority text,
country text, city text, total_amount numeric(10,2), created_at timestamptz DEFAULT now());
INSERT INTO orders (user_id, product_id, status, priority, country, city, total_amount)
SELECT (random() * 50000)::int,
(power(random(), 4) * 5000)::int,
CASE WHEN g.r < 0.45 THEN 'active' WHEN g.r < 0.75 THEN 'pending'
WHEN g.r < 0.90 THEN 'cancelled' WHEN g.r < 0.98 THEN 'completed' ELSE 'on_hold' END,
(ARRAY['low','normal','high'])[1 + (random() * 2)::int],
c.country,
c.cities[1 + (random() * 2)::int],
(random() * 500)::numeric(10,2)
FROM (SELECT random() AS r, 1 + floor(random() * 3)::int AS ci FROM generate_series(1, 200000)) g
JOIN (VALUES (1, 'USA', ARRAY['Sacramento','Fresno','Austin']),
(2, 'France', ARRAY['Paris','Lyon','Nice']),
(3, 'Vietnam', ARRAY['Hanoi','Hue','Da Nang'])) c(ci, country, cities) USING (ci);
ANALYZE orders;sql
-- PostgreSQL 18: view statistics for a column
SELECT attname, n_distinct, null_frac, avg_width, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';
-- Frequent values: most_common_vals / most_common_freqs.
-- histogram_bounds (not shown here) covers the remaining, less frequent values.
SELECT most_common_vals, most_common_freqs
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';text
-- Measured result (values vary slightly between runs because the fixture uses random()):
-- attname | n_distinct | null_frac | avg_width | correlation
-- status | 5 | 0 | 8 | 0.32
-- most_common_vals: {active,pending,cancelled,completed,on_hold}
-- most_common_freqs: {0.444,0.303,0.150,0.081,0.021}Stale Statistics Impact
When the data distribution changes after the last ANALYZE, the planner keeps using the old numbers. Fixture: on_hold is about 2% of orders, then half of all rows are updated to on_hold without a new ANALYZE.
sql
-- PostgreSQL 18 (run after the orders fixture above)
CREATE INDEX idx_orders_status ON orders (status);
ANALYZE orders;
-- Stop autovacuum from re-analyzing mid-demo; restore it at the end
ALTER TABLE orders SET (autovacuum_enabled = false);
UPDATE orders SET status = 'on_hold' WHERE id % 2 = 0;
SELECT n_mod_since_analyze FROM pg_stat_user_tables WHERE relname = 'orders';
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT * FROM orders WHERE status = 'on_hold';
ANALYZE orders;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT * FROM orders WHERE status = 'on_hold';
ALTER TABLE orders SET (autovacuum_enabled = true);text
-- Measured result:
-- before ANALYZE: Bitmap Heap Scan ... (cost=64.76..3519.10 rows=5737 width=55) (actual rows=102061.00 loops=1)
-- after ANALYZE: Seq Scan on orders (cost=0.00..5788.00 rows=101040 width=55) (actual rows=102061.00 loops=1)
-- The stale estimate (5,737) is 18x too low, so the planner chose an index-based plan for ~half the table.Per-Column Statistics Tuning
The Problem: One default_statistics_target (default 100) applies to every column. On a skewed, high-cardinality column it can be too small and the planner misestimates; on a column with 5 distinct values the default is already more than enough. ANALYZE samples roughly 300 x target rows.
sql
-- PostgreSQL 18 (run after the orders fixture; product_id is skewed there)
SHOW default_statistics_target; -- 100
ALTER TABLE orders ALTER COLUMN product_id SET STATISTICS 1;
ANALYZE orders (product_id);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT * FROM orders WHERE product_id BETWEEN 100 AND 200;
ALTER TABLE orders ALTER COLUMN product_id SET STATISTICS 1000;
ANALYZE orders (product_id);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF) SELECT * FROM orders WHERE product_id BETWEEN 100 AND 200;
-- Verify the per-column target
SELECT attname, attstattarget FROM pg_attribute
WHERE attrelid = 'orders'::regclass AND attname = 'product_id';text
-- Measured result (compare rows= estimate with actual rows=):
-- target 1: Gather (cost=1000.00..5897.92 rows=3811) (actual rows=14190.00) -- 3.7x too low
-- target 1000: Seq Scan (cost=0.00..6288.00 rows=14190) (actual rows=14190.00) -- exactRaise the target only for columns whose estimates are measurably wrong, never blindly. Risks: a higher target makes ANALYZE slower and pg_statistic bigger, and can lengthen planning time; run ANALYZE on large tables outside peak hours and watch it in pg_stat_progress_analyze. Avoid ALTER SYSTEM SET default_statistics_target for the whole server without measuring. To roll back a column: ALTER TABLE orders ALTER COLUMN product_id SET STATISTICS -1; then ANALYZE orders (product_id);.
Extended Statistics for Complex Scenarios
PostgreSQL 10+ allows statistics on column combinations (dependencies, ndistinct; mcv needs PostgreSQL 12+); statistics on expressions need PostgreSQL 14+. Run after the orders fixture above, where city determines country:
sql
-- PostgreSQL 18
-- Without extended statistics the planner multiplies the two selectivities (independence assumption)
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders WHERE country = 'USA' AND city = 'Sacramento';
CREATE STATISTICS stats_location (dependencies) ON country, city FROM orders;
ANALYZE orders;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders WHERE country = 'USA' AND city = 'Sacramento';
SELECT statistics_name, dependencies FROM pg_stats_ext WHERE tablename = 'orders';text
-- Measured result:
-- before: Gather ... rows=5478 (actual rows=16550.00) -- 3x too low
-- after: Seq Scan ... rows=16153 (actual rows=16550.00)
-- dependencies: {"7 => 6": 1.000000} -- attribute 7 (city) determines attribute 6 (country)Types of Extended Statistics:
sql
-- PostgreSQL 18
-- 1. Functional dependencies (column A determines column B); equality conditions only
CREATE TABLE employees (id serial PRIMARY KEY, department_id int, department_name text);
CREATE STATISTICS stats_dept (dependencies)
ON department_id, department_name
FROM employees;
-- 2. Multivariate MCV list (most common combinations of values, PostgreSQL 12+)
CREATE TABLE products (id serial PRIMARY KEY, product_category text, price_range text);
CREATE STATISTICS stats_purchase (mcv)
ON product_category, price_range
FROM products;
-- 3. ndistinct (distinct combinations; helps GROUP BY estimates)
CREATE STATISTICS stats_orders_nd (ndistinct)
ON user_id, product_id
FROM orders;
-- 4. Expression statistics (PostgreSQL 14+); used only when a query uses the identical expression
CREATE TABLE customers (id serial PRIMARY KEY, age int);
CREATE STATISTICS stats_age_group
ON (CASE WHEN age < 18 THEN 'child' ELSE 'adult' END)
FROM customers;
-- Extended statistics are filled by the next ANALYZE
ANALYZE employees;
ANALYZE products;
ANALYZE customers;
ANALYZE orders;Phải nhớ
ANALYZElấy mẫu khoảng 300 xdefault_statistics_targetdòng; chỉnh target theo từng cột và đorows=ước lượng so với thực tế, không tăng toàn cục.- Thống kê cũ (
n_mod_since_analyzelớn) làm planner chọn sai plan;ANALYZElại trước khi đổi index. - Cột tương quan (city -> country) cần
CREATE STATISTICS; HOT cần cả cột không index lẫn chỗ trống trong page (fillfactor).