Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use username as unique identifier/primary key

Tags:

sql

database

web

Just a quick question on the best practise for the below case.

Developing a website with accounts. Website is setup so that no two accounts can have the same username i.e. all usernames are unique.

When persisting accounts in a database, is it ok to use the username as a primary key (unique identifier) or is there some reasons I should be aware of that would require a separately generated unique id?

like image 454
Saad Attieh Avatar asked May 03 '14 00:05

Saad Attieh


1 Answers

Don't use username as primary key, never.

Use surrogate keys (ie autogenerated numbers), because

  1. they are faster and smaller (key is 4-8 bytes, username is up to you dont know bytes?)
  2. it is only right now you suppose usernames will be unique, later you will find out that you need non-unique usernames (for example for deleted users for which you have to save transaction history), or requirments will change
  3. users should be able to change their username, in case of error/typo/etc

UPDATE: in case of distributed systems, use GUIDs

like image 102
Iłya Bursov Avatar answered Oct 03 '22 07:10

Iłya Bursov