(This is in a Rails app)
Given two tables:
items
id, int(11), primary key
name, varchar(30)
choices
id, int(11), primary key
item_id, int(11), foreign key
identifier, varchar(5)
name, varchar(30)
The majority of queries against choices would be along the lines of:
SELECT identifier, name FROM choices WHERE item_id = n ORDER BY identifier;
Let’s assume that we all agree that an index can help sorting performance (I know we all don’t, that’s okay, but for this question let’s assume).
What is the best way to index choices so as to get both searching and sorting benefits:
- two indices, one on each of item_id and identifier
or
- one index on item_id, identifier
You want the composite index. With the 2 separate indexes mysql would have to choose between using an index for filtering or an index for sorting (since MySQL only uses one index per table in a query). More on how MySQL uses indexes when sorting (your case is one of the examples they give).