简体   繁体   中英

Using two primary keys in a table or similar

I have a table Users .

And I have a auto increasing long id as primary. Now I need the username also to be unique. What would be the best practice?

Should I only keep the username and remove numeric id? Should I somehow make them both unique? What do you recommend?

Maybe should also mention that using hibernate.

Typically you would add a "unique constraint" on the username. Having the auto-increment id is not strictly needed but it is a common practice to not use a "natural key". See this related question: Native primary key or auto generated one? .

To keep username unique you just need to:

ALTER TABLE Users 
ADD CONSTRAINT constraint_name UNIQUE (username);

No need to change the primary key. It is useful, to have an id primary key. And it allow you to change user names, without the need of UPDATE on linked tables.

UPD: The only case, when you wont want to keep two PK (one real, another 'semi' PK) is when the table get tons of UPDATE/INSERT/DELETE per second. In this case the overhead of 2 indexes vs 1 index can be noticeable.

It depends how your application is used. If the username can ever change I would recommend using an ID as the primary key - you can always put some checks in your code to ensure that the username is unique when it is created.

It is common practice to use an ID (primary key) when accessing data from a database as you could introduce unintended behaviour which is hard to debug if you were to use anything else.

Can the username ever change? If not, you could use it as the primary key. It would be a natural key, and as such, in my opinion, better than a surrogate key, such as you are currently using.

If the username could ever change, then it is not suitable for use as a primary key.

Since you can't know all the scenarios which could arise in the future, i suspect you can't rule out the possibility that the username might need to change. Therefore, the surrogate key is the future-proof option.

It's perfectly fine to have a unique constraint on the username even though it's not the primary key. You very likely also want a not null constraint on it.

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