What is the difference in the following two CREATE TABLE statements? (The first one uses KEY and the second one does not.)
CREATE TABLE `title` (
`title` VARCHAR(255) NOT NULL,
`order_number` VARCHAR(35) NOT NULL,
KEY `order_number` (`order_number`),
CONSTRAINT `order_number_fk` FOREIGN KEY (`order_number`)
REFERENCES `order` (`order_number`) ON DELETE CASCADE
)
CREATE TABLE `title` (
`title` VARCHAR(255) NOT NULL,
`order_number` VARCHAR(35) NOT NULL,
CONSTRAINT `order_number_fk` FOREIGN KEY (`order_number`)
REFERENCES `order` (`order_number`) ON DELETE CASCADE
)
Both of them create valid tables. How are they different and which would I want to use?
They are (almost*) the same.
When you create a foreign key constraint, an index is created on the relevant column(s) of the referencing table automatically if no suitable index already exists.
From the manual page on FOREIGN KEY Constraints:
Emphasis mine.
(*) I say almost the same because there a few subtle differences.
The name of the index
In the first version you have given the index an explicit name, but in the second version the name of the index is the same as the name of the constraint (if it is specified).
Compare the output of
SHOW INDEXin both cases:Version 1:
Version 2:
As you can see, the only difference here is the name of the index.
Silent dropping
Another subtle difference is that in the second case, as the documentation mentions, the automatically created index could be silently dropped when new indexes are added:
This means is that if you later create a multicolumn index on, for example,
(order_number, title):Then run
SHOW INDEXagain:Version 1:
Version 2:
Now you can see that the first version has two indexes but the second version has only one. With the second version, the index that was automatically created by the foreign key constraint was automatically dropped again when the multi-column index was added. Normally this isn’t a serious issue because the new index makes the original index mostly redundant.
Normally you don’t need to worry about explicitly creating the index on the referencing table of a foreign key constraint.
But you might want to create an index explicitly if: