Is it bad to use user name as primary key in database design?
Asked Answered
M

2

32

I was told by a friend:

What unique key do you use? I hope you are not saving the entire user name --- this will use up too much table space! Assign an unique userID to each (unique) userNAME and save this userID (should be INTEGER UNSIGNED auto_increment or BIGINT UNSIGNED auto_increment). Don't forget to create a reference

FOREIGN KEY (userID) REFERENCES usertable (userID) in all tables using the userID.

Is the above statement correct? Why or why not?

Muriel answered 1/12, 2009 at 11:37 Comment(0)
T
59

I think he is right ( for the wrong reason) because primary key cannot change, but username can change. So you should use userid because it wouldn't change.

Tanbark answered 1/12, 2009 at 11:37 Comment(3)
The primary key cannot change. Or it isn't "primary". The key should be system-assigned, to guarantee that it can never change. Other fields (like name) can have unique indexes, but cannot be a primary key -- by definition.Samaria
The application specifies some field as primary key and thus non changing. The application can later change, making a field originally defined as unique and non changing, to allow duplicates or to change, which is the point here.Amblyopia
It's true too for join table? In other words, should I create ID for every entry in join table because the combination of primary keys can change?Winchester
A
21

He is right for the wrong reasons. The table space is secondary to the fact that your app might later mandate that usernames can be changed or even stop being unique (you could envision an application where unique usernames are not required, like Stack Overflow) and thus your app would need major refactoring and data migration instead of a light change in the other (integer PK) case.

Amblyopia answered 1/12, 2009 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.