暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL查看执行计划及统计信息方法

IT那活儿 2023-03-21
2422
点击上方“IT那活儿”公众号,关注后了解更多内容,不管IT什么活儿,干就完了!!!

知识点描述

Postgres数据库中查看sql的执行计划等,对sql的提优具有重要意义


标准指导操作

1. 查看执行计划

1)explain analyze SQL语句
2)timing 查看SQL执行时间
3)EXPLAIN ANALYZEPERFORMANCE命令查看执行过程的瓶颈算子,然后进行针对性优化
4)关掉costs
explain (analyze on, costs off) SQL语句。
2. 统计信息方法

Part One

-- 查询某些关于表的统计信息
    select
-- 当前表所占用的数据页数量
    relpages,
-- 当前表一共有多少行组(记录)
    reltuples
    from pg_class
    where relname = 'tableName';

Part Two

-- 查询某个表的某一列的统计信息
    select
-- Null值率
    null_frac,
-- 去重后的值个数其与总元组比值的负数
    n_distinct,
-- 高频值个数,简称MCV,由default_statistics_target(默认100)决定记录多少个
    most_common_vals,
-- 高频值占比(与MCV一一对应)
    most_common_freqs,
-- 等频直方图,剔除MCV后,每个区间范围中的元素在总元组中的占比一样
    histogram_bounds,
-- 物理行序与索引行序的相关性
    correlation,
-- 平均行宽度,单位Byte
    avg_width
    from pg_stats
    where tablename = 'tableName'
    and attname = 'columnname';

Part three

-- 查询某个表的所有列的统计信息
    select attname,
-- Null值率
    null_frac,
-- 去重后的值个数其与总元组比值的负数
    n_distinct,
-- 物理行序与索引行序的相关性
    correlation,
-- 平均行宽度,单位Byte
    avg_width
    from pg_stats
    where tablename = 'tableName';

Part IV

-- 根据统计对象的名称查询
    select
-- 相当于单列统计信息的n_distinct
    stxndistinct,
-- 函数依赖度
    stxdependencies
    from pg_statistic_ext
   where stxname = #stxname#

Part Five

-- 查看统计信息更新时间 ,视图pg_stat_all_tables
    schemaname --表所在schema
    relname --表名
    last_analyze --最近一次统计信息更新时间
    last_autoanalyze --最近一次自动统计信息更新时间
select schemaname,relname,last_analyze,
last_autoanalyze from pg_stat_all_tables where schemaname='xxx' and relname = 'test';

复制

END


本文作者:魏 斌(上海新炬中北团队)

本文来源:“IT那活儿”公众号

文章转载自IT那活儿,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论