[GIS] Finding PostGIS tables that are missing indexes

postgispostgresql

Recently I was looking around in pg_stat_user_tables and was surprised to see high numbers of sequential scans on some of my spatial tables. Sure enough, these tables were missing spatial indexes.

How can I find all tables with an un-indexed geometry column?

Best Answer

Tables with missing spatial indexes can be found by querying the system tables:

SELECT g.* 
FROM 
  (SELECT 
     n.nspname, 
     c.relname, 
     c.oid AS relid, 
     a.attname, 
     a.attnum 
   FROM pg_attribute a 
   INNER JOIN pg_class c ON (a.attrelid=c.oid)
   INNER JOIN pg_type t ON (a.atttypid=t.oid)
   INNER JOIN pg_namespace n ON (c.relnamespace=n.oid) 
   WHERE t.typname='geometry' 
   AND   c.relkind='r'
 ) g 
LEFT JOIN pg_index i ON (g.relid = i.indrelid AND g.attnum = ANY(i.indkey)) 
WHERE i IS NULL;
Related Question