PostgreSQL: How to index all foreign keys?

前端 未结 3 890
南旧
南旧 2021-01-31 05:56

I am working with a large PostgreSQL database, and I am trying to tune it to get more performance.

Our queries and updates seem to be doing a lot of lookups using fore

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 06:21

    i created a script with this code, seems to be a little bit shorter:

    SELECT 'DROP INDEX IF EXISTS fk_' || conname || '_idx; CREATE INDEX fk_' || conname || '_idx ON ' 
           || relname || ' ' || 
           regexp_replace(
               regexp_replace(pg_get_constraintdef(pg_constraint.oid, true), 
               ' REFERENCES.*$','',''), 'FOREIGN KEY ','','') || ';'
    FROM pg_constraint 
    JOIN pg_class 
        ON (conrelid = pg_class.oid)
    JOIN pg_namespace
        ON (relnamespace = pg_namespace.oid)
    WHERE contype = 'f'
      AND nspname = 'public'
      --AND 'fk_' || conname || '_idx' NOT IN (SELECT indexname FROM pg_indexes)
      ;
    

    comment in the last line if you do not want to recreate already existing indexes

提交回复
热议问题