Lets say I have a simple many-to-many table between tables ‘table1’ and ‘table2’ that consists from two int fields: ‘table1-id’ and ‘table2-id’. How should I index this linking table?
I used to just make a composite primary index (table1-id,table2-id), but I read that this index might not work if you change order of the fields in the query. So what’s the optimal solution then – make independent indexes for each field without a primary index?
Thanks.
It depends on how you search.
If you search like this:
then you need:
In this case,
table1will be leading inNESTED LOOPSand your index will be usable only whentable1is indexed first.If you search like this:
then you need:
for the reasons above.
You don’t need independent indices here. A composite index can be used everywhere where a plain index on the first column can be used. If you use independent indices, you won’t be able to search efficiently for both values:
For a query like this, you’ll need at least one index on both columns.
It’s never bad to have an additional index for the second field:
Primary key will be used for searches
on both valuesand for searches based on value oftable_1, additional index will be used for searches based on value oftable_2.