Pg Stat User Tables Access Ratio
Compare sequential and index scan counts per table in pg_stat_user_tables, exposing which tables the planner reads by index and which it scans end to end.
Code
-- pg_stat_user_tables 是累积计数器:自统计重置以来的真实访问记录
SELECT
relname,
seq_scan, -- 全表顺序扫描次数
idx_scan, -- 索引扫描次数
n_live_tup, -- 估算存活行数
seq_scan + idx_scan AS total_reads,
-- 顺序扫描占比:热表长期 100% 往往意味着缺索引或查询写法问题
ROUND(
seq_scan::numeric / NULLIF(seq_scan + idx_scan, 0), 2
) AS seq_ratio,
n_tup_upd + n_tup_hot_upd AS updates_total
FROM pg_stat_user_tables
WHERE relname IN ('orders', 'customers', 'order_items')
ORDER BY seq_scan + idx_scan DESC;
-- 计数器从集群启动(或 pg_stat_reset)起累积,做对比实验前先记下基线:
-- SELECT pg_stat_reset();
-- 重置后跑一次目标查询再看增量,指向的才是这次查询的访问方式How the snippet works
At its core this is a single SELECT statement against pg_stat_user_tables.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.
Using it
Run the statement against the pg_stat_user_tables table.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which relations are involved here?
- `pg_stat_user_tables` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.