Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to add an index on a mySQL table if the ID column is the primary key?

I have a table in mySQL where the 'id' column is the PRIMARY KEY:

CREATE TABLE `USERS` (
  `ID` mediumint(9) NOT NULL auto_increment,
  .....
  PRIMARY KEY  (`ID`),
  KEY `id_index` (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=267 DEFAULT CHARSET=latin1;

I've also added an index as follows:

CREATE INDEX id_index ON USERS (id);

Did I need to do this? Or is the primary key automatically indexed?

The end aim is here is to speed up queries which join on the id column of table USERS.

Thanks

like image 471
Tenakha Avatar asked Feb 13 '13 10:02

Tenakha


1 Answers

No, you don't need do this.

Primary key is automatically indexed. What you need is to index column that is foreign key in other table.

like image 188
veljasije Avatar answered Oct 08 '22 19:10

veljasije