I know how to use INDEX as in the following code. And I know how to use foreign key and primary key.
CREATE TABLE tasks (
task_id int unsigned NOT NULL AUTO_INCREMENT,
parent_id int unsigned NOT NULL DEFAULT 0,
task varchar(100) NOT NULL,
date_added timestamp NOT NULL,
date_completed timestamp NULL,
PRIMARY KEY ( task_id ),
INDEX parent ( parent_id )
)
However I found a code using KEY instead of INDEX as following.
CREATE TABLE orders (
order_id int unsigned NOT NULL AUTO_INCREMENT,
-- etc
KEY order_date ( order_date )
)
I could not find any explanation on the official MySQL page. Could anyone tell me what is the differences between KEY and INDEX?
The only difference I see is that when I use KEY ..., I need to repeat the word, e.g. KEY order_date ( order_date ).
There’s no difference. They are synonyms, though
INDEXshould be preferred (asINDEXis ISO SQL compliant, whileKEYis a MySQL-specific, non-portable, extension).From the
CREATE TABLEmanual entry:By "The key attribute
PRIMARY KEYcan also be specified as justKEYwhen given in a column definition.", it means that these threeCREATE TABLEstatements below are equivalent and generate identicalTABLEobjects in the database:…while these 2 statements below (for
orders4,orders5) are equivalent with each other, but not with the 3 statements above, as hereKEYandINDEXare synonyms forINDEX, not aPRIMARY KEY:…as the
KEY ( order_id )andINDEX ( order_id )members do not define aPRIMARY KEY, they only define a genericINDEXobject, which is nothing like aKEYat all (as it does not uniquely identify a row).As can be seen by running
SHOW CREATE TABLE orders1...5:SHOW CREATE TABLE...orders1CREATE TABLE orders1 (order_id int NOT NULL,PRIMARY KEY ( order_id ))orders2CREATE TABLE orders2 (order_id int NOT NULL,PRIMARY KEY ( order_id ))orders3CREATE TABLE orders3 (order_id int NOT NULL,PRIMARY KEY ( order_id ))orders4CREATE TABLE orders4 (order_id int NOT NULL,KEY ( order_id ))orders5CREATE TABLE orders5 (order_id int NOT NULL,KEY ( order_id ))