美文网首页FS全栈计划
Postgres慢SQL查询与效率分析

Postgres慢SQL查询与效率分析

作者: MaxZing | 来源:发表于2019-11-21 11:09 被阅读0次
    1. 登录Postgres
    psql -h houst名称 -U 登录用户 -W
    

    输入登录密码

    1. 查询慢SQL
    SELECT substring(query, 1, 1000) AS short_query,
    round(total_time::numeric, 2) AS total_time,
    calls,
    round((100 * total_time / sum(total_time::numeric) OVER ())::numeric, 2) AS percentage_cpu
    FROM pg_stat_statements
    ORDER BY total_time DESC
    LIMIT 3;
    

    会得到执行时间最慢的3条SQL,并给出CPU占用比例
    然后选择操作表所在的数据库

    1. 数据库列表
    \l
    
    1. 选择数据库
    \c 数据库名
    
    1. 分析SQL执行
    EXPLAIN ANALYZE ***
    

    EXPLAIN ANALYZE 之后跟上需要分析的SQL语句,会得到语句执行的预计执行分析,下面是一段执行结果

    Sort  (cost=717.34..717.59 rows=101 width=488) (actual time=7.761..7.774 rows=100 loops=1)
       Sort Key: t1.fivethous
       Sort Method: quicksort  Memory: 77kB
       ->  Hash Join  (cost=230.47..713.98 rows=101 width=488) (actual time=0.711..7.427 rows=100 loops=1)
             Hash Cond: (t2.unique2 = t1.unique2)
             ->  Seq Scan on tenk2 t2  (cost=0.00..445.00 rows=10000 width=244) (actual time=0.007..2.583 rows=10000 loops=1)
             ->  Hash  (cost=229.20..229.20 rows=101 width=244) (actual time=0.659..0.659 rows=100 loops=1)
                   Buckets: 1024  Batches: 1  Memory Usage: 28kB
                   ->  Bitmap Heap Scan on tenk1 t1  (cost=5.07..229.20 rows=101 width=244) (actual time=0.080..0.526 rows=100 loops=1)
                         Recheck Cond: (unique1 < 100)
                         ->  Bitmap Index Scan on tenk1_unique1  (cost=0.00..5.04 rows=101 width=0) (actual time=0.049..0.049 rows=100 loops=1)
                               Index Cond: (unique1 < 100)
     Planning time: 0.194 ms
     Execution time: 8.008 ms
    

    会详细分析出,Join表消耗的时间,排序的时间,操作的行数,用到的索引,预计执行时间,实际执行时间等详细信息。

    相关文章

      网友评论

        本文标题:Postgres慢SQL查询与效率分析

        本文链接:https://www.haomeiwen.com/subject/qdgnictx.html