SQL reference (MySQL and MariaDB dialects)

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#

SQL
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#

NameMeaningDefault
UNIQUEDuplicate keys are refused (error 1062).off
IF NOT EXISTS, IF EXISTSSkip when the index exists / does not exist (MariaDB form).off
OR REPLACEDrop the index of that name first (MariaDB form).off
lengthPrefix length of a text column.whole column
ASC, DESCAccepted and not kept.ASC
USING, COMMENTAccepted and ignored.none
INVISIBLEKeeps the index but marks it invisible; see invisible columns and indexes.VISIBLE
(expr)A functional key part; see functional indexes.none

Remarks#

  • Privilege: INDEX on the table.
  • ALGORITHM and LOCK after DROP INDEX are read and ignored.
  • The index name is required for CREATE INDEX. The primary key is removed with ALTER 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] EXISTS and OR REPLACE; they are checked on MariaDB.

Not supported yet#

  • CREATE FULLTEXT INDEX is accepted and not kept; CREATE SPATIAL INDEX is kept as a definition (columns must be NOT NULL, error 1252).

Examples#

Example:

SQL
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

See also#