With performance improvements in mind, I was wondering if and which indexes are helpful on a join table (specifically used in a Rails 3 has_and_belongs_to_many context).
Model and Table Setup
My models are Foo
and Bar
and per rails convention, I have a join table called bars_foos
. There is no primary key or timestamps making the old fields in this table bar_id:integer
and foo_id:integer
. I'm interested in knowing which of the following indexes is best and is without duplication:
- A compound index:
add_index :bars_foos, [:bar_id, :foo_id]
- Two indexes
- A.
add_index :bars_foos, :bar_id
- B.
add_index :bars_foos, :foo_id
- A combination of both 1 and 2-B
Basically, I'm not sure if the compound index is enough assuming it is helpful to begin with. I believe that a compound index can be used as a single index for the first item which is why I am pretty sure that using all three lines would certainly result in unnecessary duplication.
Likely Usage
The most common usage will be given an instance of model Foo
, I will be asking for its associated bars
using the RoR syntax of foo.bars
and vice versa with bar.foos
for an instance of the model Bar
.
These will generate queries of the type SELECT * FROM bars_foos WHERE foo_id = ?
and SELECT * FROM bars_foos WHERE bar_id = ?
respectively and then using those resultant IDs to SELECT * FROM bars WHERE ID in (?)
and SELECT * FROM foos WHERE ID in (?)
.
Please correct me in the comments if I am incorrect, but I do not believe that, in the context of the Rails application, it is ever going to try to do a query where it specifies both IDs like SELECT * FROM bars_foos where bar_id = ? AND foo_id = ?
.
Databases
In the event there are database specific optimization techniques, I will most likely be using PostgreSQL. However, others using this code may want to use it in MySQL or SQLite depending on their Rails configuration so all answers are appreciated.