In the documentation, it says
“In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index.”
This implies to me that the primary key data is appended to the secondary index where the data is already sorted. But when I use a leftmost prefix of a composite index only then sort the result by primary key, the optimizer wants to sort the data which seems to imply that the primary key is not appended to the secondary index?
Setup:
CREATE TABLE `test` (
`ID` int NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `Name` (`Name`),
KEY `Name_CountryCode` (`Name`, `CountryCode`)
) ENGINE=InnoDB;
INSERT INTO test VALUES (1, 'a', 'b');
INSERT INTO test VALUES (2, 'c', 'd');
Query 1: Use secondary index ‘Name’, then sort by primary key
mysql> EXPLAIN SELECT * FROM test WHERE Name = 'a' ORDER BY ID\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test
partitions: NULL
type: ref
possible_keys: Name,Name_CountryCode
key: Name
key_len: 140
ref: const
rows: 1
filtered: 100.00
Extra: Using index condition
1 row in set, 1 warning (0.00 sec)
- As expected, there is no filesort in the Extra field since the primary key is already appended to the secondary index
Query 2: Use the composite index ‘Name_CountryCode’, then sort by primary key
mysql> EXPLAIN SELECT * FROM test USE INDEX (Name_CountryCode) WHERE Name = 'a' ORDER BY ID\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test
partitions: NULL
type: ref
possible_keys: Name_CountryCode
key: Name_CountryCode
key_len: 140
ref: const
rows: 1
filtered: 100.00
Extra: Using where; Using index; Using filesort
1 row in set, 1 warning (0.00 sec)
- shouldn’t there be no filesort here since the primary key is already appended to the secondary index?