Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql unique key and index

Tags:

mysql

in MySQL, If I create a unique key on two columns, say

UNIQUE KEY my_key (column1, column2)

is it necessary to build another key on column1? My goal is to have column1 and column2 to be unique, and I'll do lots of selects keyed by column1.

like image 803
Beier Avatar asked Mar 10 '10 21:03

Beier


2 Answers

No, it is not necessary because an index on (column1, column2) can be used instead of an index of column1 alone.

You might want to make a new index on just column two though as the index (column1, column2) is not good when searching only for (column2).

like image 102
Mark Byers Avatar answered Oct 26 '22 23:10

Mark Byers


No, your my_key index takes care of any queries on column1 or conditions on column1 AND column2. However, if you make queries on only column2, then you should add an additional index for column2 to be able to query it efficiently.

Furthermore, if both column1 and column2 are unique, then you might want to consider using something like

[...]
UNIQUE(column1),
UNIQUE(column2),
PRIMARY KEY (column1, column2);

This ensures that both column1 and column2 are unique, and any query selecting only column1 and column2 can be retrieved using index-only access.

like image 35
PatrikAkerstrand Avatar answered Oct 26 '22 21:10

PatrikAkerstrand