Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL "KEY" keyword

Tags:

mysql

CREATE TABLE IF NOT EXISTS `scores` (
  `userID` int(11) NOT NULL,
  `sessionID` int(11) NOT NULL,
  `points` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`userID`,`sessionID`),
  KEY `par_ind1` (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

What does the line:

KEY `par_ind1` (`userID`)

do? (userID is a primary key in another table?)

like image 533
Caner Avatar asked Apr 29 '12 14:04

Caner


2 Answers

KEY is a synonym for INDEX. This creates an index named par_ind1 ont the column userID in addition to the composite key it already shares with sessionID.

See the MySQL CREATE TABLE documentation for the full details, but the relevant part here is:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    { LIKE old_tbl_name | (LIKE old_tbl_name) }
create_definition:
    col_name column_definition
  | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...)
      [index_option] ...

  /* Key/Index creation */
  | {INDEX|KEY} [index_name] [index_type] (index_col_name,...)
      [index_option] ...

Since no index_type was specified, the default is used. See the CREATE INDEX reference for the default index types, which vary by table storage engine. For an InnoDB table such as this, that's a BTREE index.

like image 180
Michael Berkowski Avatar answered Sep 30 '22 20:09

Michael Berkowski


It creates a secondary, non-unique index on this column. You can use INDEX and KEY interchangeably in this context.

like image 40
Mchl Avatar answered Sep 30 '22 18:09

Mchl