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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which relations are involved here?
`pg_stat_user_tables` — referenced directly, no join needed.