Home > Database > Mysql Tutorial > What\'s the Difference Between `INDEX` and `KEY` in MySQL?

What\'s the Difference Between `INDEX` and `KEY` in MySQL?

Susan Sarandon
Release: 2024-11-24 22:37:10
Original
774 people have browsed it

What's the Difference Between `INDEX` and `KEY` in MySQL?

The difference between INDEX and KEY in MySQL

In MySQL, INDEX and KEY are synonyms used to improve query performance, they have no essence the difference. However, for ISO SQL compatibility reasons, using INDEX is preferred.

The description of CREATE TABLE in the MySQL manual states: "KEY is usually a synonym for INDEX. When specified in the column definition, the primary key attribute PRIMARY KEY can also be specified as KEY. This is for compatibility with other database systems. Implemented. ”

For example, the following three CREATE TABLE statements are equivalent and produce the same table object in the database:

CREATE TABLE orders1 (
    order_id int PRIMARY KEY
);

CREATE TABLE orders2 (
    order_id int KEY
);

CREATE TABLE orders3 (
    order_id int NOT NULL,

    PRIMARY KEY ( order_id )
);
Copy after login

On the other hand, the following two statements are equivalent but different from the above three statements:

CREATE TABLE orders4 (
    order_id int NOT NULL,

    KEY ( order_id )
);

CREATE TABLE orders5 (
    order_id int NOT NULL,

    INDEX ( order_id )
);
Copy after login

This is because in these statements, KEY and INDEX are synonyms of INDEX, not PRIMARY KEY. Therefore, the KEY ( order_id ) and INDEX ( order_id ) members do not define a primary key, they only define a generic index object, which is completely different from KEY (because it does not uniquely identify a row).

You can verify this by running the SHOW CREATE TABLE orders1...5 command:

CREATE TABLE orders1 (
    order_id int NOT NULL,
    PRIMARY KEY ( order_id )
)


CREATE TABLE orders2 (
    order_id int NOT NULL,
    PRIMARY KEY ( order_id )
)


CREATE TABLE orders3 (
    order_id int NOT NULL,
    PRIMARY KEY ( order_id )
)


CREATE TABLE orders4 (
    order_id int NOT NULL,
    KEY ( order_id )
)


CREATE TABLE orders5 (
    order_id int NOT NULL,
    KEY ( order_id )
)
Copy after login

The above is the detailed content of What\'s the Difference Between `INDEX` and `KEY` in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template