Search This Blog

Friday, July 21, 2017

Postgres SQL: Indexes

invalid indexes:

select count(*) from pg_index where indisvalid = false



number of indexes per tables:

select tablename, count(*) from pg_indexes where schemaname != 'pg_catalog' group by tablename having count(*) > 4 order by 2 desc;
   tablename   | count
---------------+-------
 table1      |    18
 table2         |    18
 table3 |    15
 table4        |    13


Index usage

SELECT
    i.idx_scan,
    i.idx_tup_read,
    i.idx_tup_fetch,
    i.indexrelname AS index,
    it.spcname AS index_tablespace,
    i.relname AS table,
    tt.spcname AS table_tablespace,
    pg_size_pretty(pg_relation_size(i.indexrelname::text)) as index_size
FROM pg_stat_all_indexes i
    INNER JOIN pg_class ic ON (i.indexrelid = ic.oid)
    LEFT OUTER JOIN pg_tablespace it ON (ic.reltablespace = it.oid)
    INNER JOIN pg_class tc ON (i.relid = tc.oid)
    LEFT OUTER JOIN pg_tablespace tt ON (tc.reltablespace = tt.oid)
ORDER BY 1 desc, 2 desc, 3 desc


Index not used

select * from pg_stat_all_indexes
where schemaname <> 'pg_catalog'
and schemaname <> 'pg_toast'
and idx_scan = 0
and idx_tup_read = 0
and idx_tup_fetch = 0
and indexrelid not in (select indexrelid from pg_index where indisunique = true or indisprimary = true
);


No comments:

Post a Comment