Does Postgres automatically put indexes on Foreign Keys and Primary Keys? How can I tell? Is there a command that will return all indexes on a table?
Does Postgres automatically put indexes on Foreign Keys and Primary Keys? How can I
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships.
When Pg creates an implicit index it will emit a
NOTICE-level message that you can see inpsqland/or the system logs, so you can see when it happens. Automatically created indexes are visible in\doutput for a table, too.The documentation on unique indexes says:
and the documentation on constraints says:
Therefore you have to create indexes on foreign-keys yourself if you want them.
Note that if you use primary-foreign-keys, like 2 FK’s as a PK in a M-to-N table, you will have an index on the PK and probably don’t need to create any extra indexes.
While it’s usually a good idea to create an index on (or including) your referencing-side foreign key columns, it isn’t required. Each index you add slows DML operations down slightly, so you pay a performance cost on every
INSERT,UPDATEorDELETE. If the index is rarely used it may not be worth having.