时间:2010-07-23 13:51:09

标签: sql database-design postgresql

10 个答案:

答案 0 :(得分:146)

我喜欢这样找到缺失的索引:

SELECT
  relname                                               AS TableName,
  to_char(seq_scan, '999,999,999,999')                  AS TotalSeqScan,
  to_char(idx_scan, '999,999,999,999')                  AS TotalIndexScan,
  to_char(n_live_tup, '999,999,999,999')                AS TableRows,
  pg_size_pretty(pg_relation_size(relname :: regclass)) AS TableSize
FROM pg_stat_all_tables
WHERE schemaname = 'public'
      AND 50 * seq_scan > idx_scan -- more then 2%
      AND n_live_tup > 10000
      AND pg_relation_size(relname :: regclass) > 5000000
ORDER BY relname ASC;

这将检查是否有更多的序列扫描然后索引扫描。如果表很小,它会被忽略,因为Postgres似乎更喜欢对它们进行序列扫描。

以上查询确实显示缺失的索引。

下一步是检测缺失的组合索引。我想这不容易,但可行。也许分析缓慢的查询...我听说pg_stat_statements可以帮助......

答案 1 :(得分:17)

答案 2 :(得分:8)

答案 3 :(得分:6)

用于分析PostgreSQL的另一个新的有趣工具是PgHero。它更侧重于调整数据库并进行大量分析和建议。

screenshot

答案 4 :(得分:3)

答案 5 :(得分:3)

您可以使用以下查询来查找索引使用情况和索引大小:

Reference is taken from this blog.

SELECT
    pt.tablename AS TableName
    ,t.indexname AS IndexName
    ,to_char(pc.reltuples, '999,999,999,999') AS TotalRows
    ,pg_size_pretty(pg_relation_size(quote_ident(pt.tablename)::text)) AS TableSize
    ,pg_size_pretty(pg_relation_size(quote_ident(t.indexrelname)::text)) AS IndexSize
    ,to_char(t.idx_scan, '999,999,999,999') AS TotalNumberOfScan
    ,to_char(t.idx_tup_read, '999,999,999,999') AS TotalTupleRead
    ,to_char(t.idx_tup_fetch, '999,999,999,999') AS TotalTupleFetched
FROM pg_tables AS pt
LEFT OUTER JOIN pg_class AS pc 
    ON pt.tablename=pc.relname
LEFT OUTER JOIN
( 
    SELECT 
        pc.relname AS TableName
        ,pc2.relname AS IndexName
        ,psai.idx_scan
        ,psai.idx_tup_read
        ,psai.idx_tup_fetch
        ,psai.indexrelname 
    FROM pg_index AS pi
    JOIN pg_class AS pc 
        ON pc.oid = pi.indrelid
    JOIN pg_class AS pc2 
        ON pc2.oid = pi.indexrelid
    JOIN pg_stat_all_indexes AS psai 
        ON pi.indexrelid = psai.indexrelid 
)AS T
    ON pt.tablename = T.TableName
WHERE pt.schemaname='public'
ORDER BY 1;

答案 6 :(得分:2)

可以通过在postgres控制台中使用以下查询来找到它

use db_name
select * from pg_stat_user_indexes;
select * from pg_statio_user_indexes;

有关更多详细信息,https://www.postgresql.org/docs/current/monitoring-stats.html

答案 7 :(得分:0)

对于PostgreSQL 9.4+来说,

PoWA似乎是一个有趣的工具。它收集统计信息,可视化它们并建议索引。它使用pg_stat_statements扩展名。

  

PoWA是PostgreSQL工作负载分析器,可收集性能统计数据并提供实时图表和图形,以帮助监控和调整PostgreSQL服务器。它类似于Oracle AWR或SQL Server MDW。

答案 8 :(得分:0)

CREATE EXTENSION pgstattuple; 
CREATE TABLE test(t INT); 
INSERT INTO test VALUES(generate_series(1, 100000)); 
SELECT * FROM pgstatindex('test_idx'); 

version            | 2 
tree_level         | 2 
index_size         | 105332736 
root_block_no      | 412 
internal_pages     | 40 
leaf_pages         | 12804 
empty_pages        | 0 
deleted_pages      | 13 
avg_leaf_density   | 9.84 
leaf_fragmentation | 21.42 

答案 9 :(得分:-1)