简体   繁体   中英

MySQL UNIQUE and INDEX use on Column

I would like to add a index for quick lookups and uniqueness for a column called "Username". I see an option to choose UNIQUE or INDEX . Should I create both, or just go with UNIQUE?

I am not using username as a primary key guys.

In MySQL under the hood whenever you make an attribute UNIQUE it will be INDEX -ed too. Some database designer like to explicitly define UNIQUE attributes also as INDEX , but whatever your choice the result will be the same.

UNIQUE creates an INDEX automatically for most dbs. So to answer you, you should create just one, which is UNIQUE . You can find a relevant thread here for MySQL

A primary key on a table is also automatically an index in mySql. So if you want to have a column be an index, and a unique key, then you can create a table like this:

 CREATE TABLE `users` (
    `username`,
     PRIMARY KEY (`username`),
     UNIQUE KEY `new_mmp_id` (`username`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1

So in the end, you have an index on the username field that is a unique field itself. It is also the primary key, which is an index automatically. You never explained the specific fields in the table, like if you need an auto incremental id field

Should I create both, or just go with UNIQUE?

If you must have unique fields on the username column, then you should def. create both, if not then just set the username to the primary key which is an index.

I suggest your read this article http://www.xaprb.com/blog/2009/09/12/the-difference-between-a-unique-index-and-primary-key-in-mysql/

What are differences between Index vs Key in MySQL

My hunch is UNIQUE will give you the best performance boost, but INDEX would also give a boost. I think the only reason you wouldn't want to use UNIQUE is if you don't want MySQL to handle checking for unique values whenever you do an INSERT or an UPDATE .

I don't think you need both. But I'm no expert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM