CREATE INDEX and DROP INDEX statements
Create and drop plain, unique, prefix, invisible and functional indexes, and how they map to ALTER TABLE.
CREATE INDEX adds a secondary index to a table; DROP INDEX removes one. Both are rewritten into ALTER TABLE and behave like the matching ALTER TABLE change.
Syntax#
CREATE [OR REPLACE] [UNIQUE] INDEX [IF NOT EXISTS] index_name
ON [db_name.]tbl_name (key_part, ...)
[index_option] ...
key_part:
{ col_name [(length)] | (expr) } [ASC | DESC]
index_option:
USING { BTREE | HASH } | COMMENT 'string' | VISIBLE | INVISIBLE
DROP INDEX [IF EXISTS] index_name ON [db_name.]tbl_name
[{ ALGORITHM | LOCK } [=] value] ...Arguments#
| Name | Meaning | Default |
|---|---|---|
UNIQUE | Duplicate keys are refused (error 1062). | off |
IF NOT EXISTS, IF EXISTS | Skip when the index exists / does not exist (MariaDB form). | off |
OR REPLACE | Drop the index of that name first (MariaDB form). | off |
length | Prefix length of a text column. | whole column |
ASC, DESC | Accepted and not kept. | ASC |
USING, COMMENT | Accepted and ignored. | none |
INVISIBLE | Keeps the index but marks it invisible; see invisible columns and indexes. | VISIBLE |
(expr) | A functional key part; see functional indexes. | none |
Remarks#
- Privilege:
INDEXon the table. ALGORITHMandLOCKafterDROP INDEXare read and ignored.- The index name is required for
CREATE INDEX. The primary key is removed withALTER TABLE ... DROP PRIMARY KEY. - Making a unique index over rows that already break it fails with MySQL's error 1062 and leaves no index.
- The parser does not test the dialect for
IF [NOT] EXISTSandOR REPLACE; they are checked on MariaDB.
Not supported yet#
CREATE FULLTEXT INDEXis accepted and not kept;CREATE SPATIAL INDEXis kept as a definition (columns must beNOT NULL, error 1252).
Examples#
Example:
CREATE TABLE a (id int PRIMARY KEY, n int, KEY kn (n), UNIQUE KEY un (id, n));
DROP INDEX kn ON a;
SHOW INDEX FROM a;
CREATE INDEX k3 ON t ((b DIV 10));
CREATE INDEX ib2 ON t (a) INVISIBLE;
CREATE INDEX IF NOT EXISTS ix2 ON t (y); -- MariaDB
CREATE OR REPLACE INDEX ix2 ON t (y2); -- MariaDB
DROP INDEX IF EXISTS ix2 ON t; -- MariaDB