Say I have a 1-to-N relationship (person_id, pet_id)
. I have a table where pet_id
is the primary key.
I understand that an InnoDB secondary index is essentially a B-tree where the values are the corresponding primary key values for the row.
Now, suppose one person can have thousands of pets and I often want a person's pets in order of pet_id
. Then it would matter if records in the secondary index are sorted by (person_id, pet_id)
or just person_id
with the pet_id
's for that person_id
being unsorted. Guessing the later.
So, if person_id
is non-unique, are records physically sorted by (person_id, pet_id)
or JUST pet_id
?
Thanks
Best Answer
No. If your table has the InnoDB engine and the
PRIMARY KEY
is(pet_id)
, then defining a secondary index as(person_id)
or(person_id, pet_id)
makes no difference.The index includes the
pet_id
column as well so values are sorted as(person_id, pet_id)
in both cases.A query like the one you have:
will need to access only the index to get the values and even more, it won't need to do any sort, as the
pet_id
values are already sorted in the index. You can verify this by looking at the execution plans (EXPLAIN
):First, we try with a MyISAM table:
Notice the filesort!
Now, MyISAM with composite index:
Filesort is gone, as expected.
Now lets try the same with InnoDB engine:
No filesort either! Even though the index does not explicitly have the
pet_id
column, the values are there and sorted. You can check that if you define the index with(person_id, pet_id)
, theEXPLAIN
is identical.Lets actually do it, with InnoDB and the composite index:
Identical plans with the previous case.
To be 100% sure, I also run the last 2 cases (InnoDB engine, with single and composite indexes) enabling the
file_per_table
setting and adding a few thousands rows in the table:In both cases, checking the actual file sizes, yields identical results: