I have a user table with userid and username columns, and both are unique.
Between userid and username, which would be better to use as a foreign key and why?
My Boss wants to use string, is that ok?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends
There are many existing discussions on the trade-offs between Natural and Surrogate Keys – you will need to decide on what works for you, and what the ‘standard’ is within your organisation.
In the OP’s case, there is both a surrogate key (
int userId) and a natural key (charorvarchar username). Either column can be used as a Primary key for the table, and either way, you will still be able to enforce uniqueness of the other key.Here are some considerations when choosing one way or the other:
The case for using Surrogate Keys (e.g. UserId INT AUTO_INCREMENT)
If you use a surrogate, (e.g.
UserId INT AUTO_INCREMENT) as the Primary Key, then all tables referencing tableMyUsersshould then useUserIdas the Foreign Key.You can still however enforce uniqueness of the
usernamecolumn through use of an additional unique index, e.g.:As per @Dagon, using a narrow primary key (like an
int) has performance and storage benefits over using a wider (and variable length) value likevarchar. This benefit also impacts further tables which referenceMyUsers, as the foreign key touseridwill be narrower (fewer bytes to fetch).Another benefit of the surrogate integer key is that the username can be changed easily without affecting tables referencing
MyUsers.If the
usernamewas used as a natural key, and other tables are coupled toMyUsersviausername, it makes it very inconvenient to change a username (since the Foreign Key relationship would otherwise be violated). If updating usernames was required on tables usingusernameas the foreign key, a technique like ON UPDATE CASCADE is needed to retain data integrity.The case for using Natural Keys (i.e. username)
One downside of using Surrogate Keys is that other tables which reference
MyUsersvia a surrogate key will need to beJOINed back to theMyUserstable if theUsernamecolumn is required. One of the potential benefits of Natural keys is that if a query requires only theUsernamecolumn from a table referencingMyUsers, that it need not join back toMyUsersto retrieve the user name, which will save some I/O overhead.