1. 程式人生 > >查詢postgresql耗時最慢的SQL

查詢postgresql耗時最慢的SQL

    PostgreSQL部署上之後,經過一段時間的執行,我們比較關心那些SQL執行時間比較長,或者說那些SQL執行的特別慢,拖累的效能,只有找到這些SQL,才能有針對性地對這些SQL進行優化,提升PostgreSQL的效能。
   PostgreSQL提供了pg_stat_statements來儲存SQL的執行次數,總執行時間,shared_buffer命中次數,shared_buffer read次數等統計資訊。

Name Type References Description
userid oid pg_authid.oid OID of user who executed the statement
dbid oid pg_database.oid OID of database in which the statement was executed
query text   Text of the statement (up to track_activity_query_size
 bytes)
calls bigint   Number of times executed
total_time double precision   Total time spent in the statement, in seconds
rows bigint   Total number of rows retrieved or affected by the statement
shared_blks_hit bigint   Total number of shared blocks hits by the statement
shared_blks_read bigint   Total number of shared blocks reads by the statement
shared_blks_written bigint   Total number of shared blocks writes by the statement
local_blks_hit bigint   Total number of local blocks hits by the statement
local_blks_read bigint   Total number of local blocks reads by the statement
local_blks_written bigint   Total number of local blocks writes by the statement
temp_blks_read bigint   Total number of temp blocks reads by the statement
temp_blks_written bigint   Total number of temp blocks writes by the statemen

   上圖表來自PostgreSQL官方文件,注意的一點是,我的PostgreSQL是9.1.9,此時total_time的單位是秒,我觀9.2的PostgreSQL的文件,total_time單位已經是毫秒。所以我的參考文獻More On PostgreSQL perform 裡面應該用的是9.2,因為外國這位大神預設單位是毫秒。
   可以看出,pg_stat_statements統計了SQL的很多資訊,方便我們分析SQL的效能。但是這個屬於PostgreSQL的擴充套件,需要修改postgresql.conf,才能使用:
操作步驟如下
    1 修改配置檔案,並且重啟PostgreSQL方能生效

  1. #------------------------------------------------------------------------------
  2. # PG_STAT_STATEMENTS OPTIONS
  3. #------------------------------------------------------------------------------
  4. shared_preload_libraries = 'pg_stat_statements'
  5. custom_variable_classes = 'pg_stat_statements'
  6. pg_stat_statements.max = 1000
  7. pg_stat_statements.track = all

    2 建立pg_stat_statements擴充套件

  1. CREATE EXTENSION pg_stat_statements;

    從此之後,PostgreSQL就能記錄SQL的統計資訊。
   上面的表格雖然豐富,其實我們基本比較關心執行最慢的SQL,如何檢視執行最慢的10條SQL?

SELECT  query, calls, total_time, (total_time/calls) as average ,rows, 
        100.0 * shared_blks_hit /nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent 
FROM    pg_stat_statements 
ORDER   BY average DESC LIMIT 10;

    我在我本地的DB,查詢最慢的2條SQL,輸出如下:
   
   在我另一臺機器上,用pgadmin檢視:
   
    統計結果一直都在,重啟也不會清零,那麼統計結果如何清零重新統計呢?執行下面SQL即可:

  1. select pg_stat_statements_reset() ;

    找到最耗時的SQL,我們就能針對這些耗時的SQL,檢視是否有優化的餘地。

參考文獻:
More on Postgres Performance
2   PostgreSQL manual