I am learning from a tutorial that uses INDEX()
within a CREATE TABLE
statement, but does not explain whether it is clustered or non-clustered. My question is: does INDEX()
when used in a CREATE TABLE
statement result in a clustered or non-clustered index?
For example:
CREATE TABLE test (a varchar(30), b varchar(30), index(a));
/* Is column A a clustered or non-clustered index? */
Also wondering how to do the opposite as well: if the example results in a non-clustered index, how do you write a clustered index, and vice versa?
TL;DR The primary key - and only the primary key - is a clustered index. If you don't explicitly define a primary key, the first suitable
UNIQUE
key is used. If you don't have either a primary key or a suitableUNIQUE
key, MySQL generates a hidden clustered index. You cannot create a clustered index usingINDEX()
.As explained in the docs (emphasis added):
See also the definition of clustered index in the glossary, which defines it as "The InnoDB term for a primary key index," along with some additional details.
So, to answer your question, there's no way to create a clustered index, other than to create a primary key or, on a table without a primary key, a suitable
UNIQUE
key (all key columns NOT NULL).INDEX()
just creates a secondary (i.e., non-clustered) key, no matter what you do with it.* Note: as pointed out in the comments, some other databases don't have clustered indexes, at all, and some allow more than one clustered index on a table. I'm only addressing MySQL in my answer.