Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Index Usage Analysis

Is there a tool or method to analyze Postgres, and determine what missing indexes should be created, and which unused indexes should be removed? I have a little experience doing this with the "profiler" tool for SQLServer, but I'm not aware of a similar tool included with Postgres.

like image 942
Cerin Avatar asked Jul 23 '10 13:07

Cerin


People also ask

How does Postgres decide which index to use?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.

How do I find the index size in PostgreSQL?

PostgreSQL index size To get total size of all indexes attached to a table, you use the pg_indexes_size() function. The pg_indexes_size() function accepts the OID or table name as the argument and returns the total disk space used by all indexes attached of that table.

Which index is best in PostgreSQL?

B-tree indexes B-tree is the default index in Postgres and is best used for specific value searches, scanning ranges, data sorting or pattern matching.

What is the most common index type used in PostgreSQL?

The most common and widely used index type is the B-tree index. This is the default index type for the CREATE INDEX command, unless you explicitly mention the type during index creation.


Video Answer


1 Answers

I like this to find missing indexes:

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 than 2%       AND n_live_tup > 10000       AND pg_relation_size(relname :: regclass) > 5000000 ORDER BY relname ASC; 

This checks if there are more sequence scans than index scans. If the table is small, it gets ignored, since Postgres seems to prefer sequence scans for them.

Above query does reveal missing indexes.

The next step would be to detect missing combined indexes. I guess this is not easy, but doable. Maybe analyzing the slow queries ... I heard pg_stat_statements could help...

like image 162
guettli Avatar answered Oct 01 '22 12:10

guettli