I have the following table (there are more columns in the real one).
CREATE TABLE `test`.`j_data` (
`j_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`j_name` VARCHAR(80) NULL DEFAULT NULL
PRIMARY KEY (`j_id`));
We regularly run queries where the main column used is the PK, e.g.
SELECT * FROM j_data WHERE j_id = 123;
But we are now looking to run a lot of queries like:
SELECT j_id FROM j_data WHERE j_name = xxx;
Would this benefit from a covering index on j_name
and j_id
.
ADD INDEX `j_name_id` (`j_name` ASC, `j_id` ASC);
Or would an index on j_name
only suffice? It's quite a large table so I don't want to spend time adding the index if it is unlikely to help.
Best Answer
Short answer: Yes.
Long answer:
You are using InnoDB, correct? (Run
SHOW CREATE TABLE j_data
to find out what the Engine is.)In InnoDB, each "secondary index" (contrast "primary key") silently contains a copy of the primary key.
So...
INDEX(j_name)
happens to be identical toINDEX(j_name, j_id)
.Tip: At some point you will realize that prefixing all columns with the table name ("j_") is unnecessary clutter.