1. 程式人生 > >PostgreSQL查看索引的使用情況

PostgreSQL查看索引的使用情況

init postgres 通過 where 刪除 seek odi exe isnull

--==========================================
--查看索引的使用情況
--索引在重建或刪除新建時sys.dm_db_index_usage_stats中相關的數據會被清除
--索引在重整是不會清除sys.dm_db_index_usage_stats的數據
SELECT  DB_NAME(ixu.database_id) DataBase_Name ,
        OBJECT_NAME(ixu.object_id) Table_Name ,
        ix.name Index_Name ,
        ( SELECT    MAX(s.rows)
          FROM      sysindexes s
          WHERE     s.id 
= ixu.object_id ) AS Table_Rows , STATS_DATE(ixu.object_id, ixu.index_id) AS statistic_time , ixu.user_updates , ixu.last_user_update , ixu.last_user_seek , ixu.user_seeks , ixu.last_user_scan , ixu.user_scans , ixu.last_user_lookup , ixu.user_lookups , ixu.user_updates
/ ( ISNULL(ixu.user_seeks, 0) + ISNULL(ixu.user_scans, 0) + 1 ) AS UseRate FROM sys.dm_db_index_usage_stats ixu INNER JOIN sys.indexes ix ON ixu.object_id = ix.object_id AND ixu.index_id = ix.index_id INNER JOIN sys.objects ob ON ixu.object_id
= ob.object_id WHERE ob.type = U AND ob.is_ms_shipped = 0 AND ixu.database_id = DB_ID() --AND ix.object_id=OBJECT_ID(TableName)

存放索引詳細信息的表

data_name=# \d+ pg_stat_user_indexes;
           View "pg_catalog.pg_stat_user_indexes"
    Column     |  Type  | Modifiers | Storage | Description 
---------------+--------+-----------+---------+-------------
 relid         | oid |           | plain | 
 indexrelid    | oid |           | plain | 
 schemaname    | name |           | plain | 
 relname       | name |           | plain | 
 indexrelname  | name |           | plain | 
 idx_scan      | bigint |           | plain | 
 idx_tup_read  | bigint |           | plain | 
 idx_tup_fetch | bigint |           | plain | 
View definition:
 SELECT pg_stat_all_indexes.relid,
    pg_stat_all_indexes.indexrelid,
    pg_stat_all_indexes.schemaname,
    pg_stat_all_indexes.relname,
    pg_stat_all_indexes.indexrelname,
    pg_stat_all_indexes.idx_scan,
    pg_stat_all_indexes.idx_tup_read,
    pg_stat_all_indexes.idx_tup_fetch
   FROM pg_stat_all_indexes
  WHERE (pg_stat_all_indexes.schemaname <> ALL (ARRAY[pg_catalog::name, information_schema::name])) AND pg_stat_all_indexes.schemaname !~ ^pg_toast::text;

通過這個表查看某個表的索引使用情況易如反掌了。

示例一、查看所有表的索引的使用情況

select relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch from pg_stat_user_indexes order by idx_scan asc, idx_tup_read asc, idx_tup_fetch asc;

示例二、查看某個表的索引使用情況

select relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch from pg_stat_user_indexes where relname = table_name order by idx_scan asc, idx_tup_read asc, idx_tup_fetch asc;

PostgreSQL查看索引的使用情況