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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With