Raja's Exocortex

Postgres Performance

SQL snippets and guidelines on troubleshooting Postgres DB performance issues.

Identifying Table Scans

Prerequisites: pg_stat_statements must be enabled.


select seq_scan, n_live_tup, relname  
  from pg_stat_user_tables  
  order by seq_scan desc  
  limit 10;  
> seq_scan | n_live_tup | relname  
> ----------+------------+--------------------  
> 81264339 | 20 | MaintCode  
> 16840299 | 3  | DbTranImageStatus  
> 14905181 | 18 | ControlFeature  
> 11908114 | 10 | AgingBoundary  
> 8789288  | 22 | CtofcTypeCode  
> 7786110  | 6  | PrefCounty  
> 6303959  | 9  | ProtOrderHistEvent  
> 5835430  | 1  | ControlRecord  
> 5466806  | 1  | ControlAccounting  
> 5202028  | 12 | ProtEventOrderType  
> (10 rows)

Show Tables/Columns and their Indexes

-- Note: this displays indexes on all tables like 'test%'

select
    t.relname as table_name,
    i.relname as index_name,
    array_to_string(array_agg(a.attname), ', ') as column_names
from
    pg_class t,
    pg_class i,
    pg_index ix,
    pg_attribute a
where
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and a.attrelid = t.oid
    and a.attnum = ANY(ix.indkey)
    and t.relkind = 'r'
    and t.relname like 'test%'
group by
    t.relname,
    i.relname
order by
    t.relname,
    i.relname;

 table_name | index_name | column_names
------------+------------+--------------
 test       | pk_test    | a, b
 test2      | uk_test2   | b, c
 test3      | uk_test3ab | a, b
 test3      | uk_test3b  | b
 test3      | uk_test3c  | c

References

  1. List Columns with Indexes in Postgres
  2. Does Postgresql keep track of full table scans it makes

#postgres #performance-tuning