Home > OS >  Does PostgreSQL use all available indexes to run a query faster?
Does PostgreSQL use all available indexes to run a query faster?

Time:08-18

We are structuring a project where some tables will have many records, and we intend to use 4 numeric foreign keys and 1 numeric primary, our assumption is that if we create an index for each foreign key and the default index of the primary key, the postgres planning would use all the starts (5 in total) to perform the query.

95% of the time the queries would be providing at least the 4 foreign keys.

  1. Would each index be used to position the search faster in the sequential section of records?
  2. Would having 4 indexes increase the speed of the query or would it suffice with a single index of the parent level (branch_id)?

Thank you for your time and experience.

table

CodePudding user response:

Indexes are (predominantly) used when filtering or joining tables, so whether the indexes you are proposing are useful is entirely dependent on the SQL you are running and whether the query optimiser determines that using an index would be beneficial.

For example, if you ran SELECT * FROM TABLE then none of the indexes would be used.

I can’t comment on Postgresql specifically but many/most DBMSs automatically create indexes when you define PKs/FKs - so you will get the indexes anyway, regardless of any performance tuning you are trying to implement

CodePudding user response:

If all 4 columns are specified by equality, it is possible to combine the single-column indexes using BitmapAnd. However, this would be less efficient than using one multi-column index on all four columns.

Since that will apparently be a very common query, it would make sense to have that multi-column index.

Usually you will want to index each foreign key column. Otherwise, if you want to delete an organization, for example, it would need to scan the whole table to verify that no records were still referencing it. Whichever column is the first one in the multi-column index will not need to also have a single-column index for it. But the other 3 which are not first probably still need their own indexes.

  • Related