Possible Duplicate:
How to choose my primary key?
I have a User class with the following attributes:
- Username (unique)
- Password
- Email (unique)
- First Name
- Last Name
- Age
Username and Email uniquely identify an instance of User. In my database, should these be used as a primary key or should I generate a different unique identifier for each instance. As far as I know, on SELECT‘s, comparing strings is slower than comparing numbers. Shouldn’t I then use a self-assigned int, long, double, etc. or use the AUTO_INCREMENT in a ID column for Users? What about using UUIDs (again the issue with long strings)? My question also applies to every other domain class I might add later.
The primary key should be separate from any other field, should have no business value and should be a unique integer.
Example: A company creates a ‘user’ table with social security numbers. These should be unique to each person. However, at some point a ssn is mis-keyed when being entered by a user. The mis-keyed number doesn’t already exists and the record is saved. Some time later another user tries to enter their ssn, and it is actually the same number as was mis-keyed earlier. The user may not be able to actually save their profile and continue until the company itself finds and resolves this issue. The company decides to relax the ‘unique’ constraint on ssn at this point, given this issue. If the ssn is NOT the primary key this will be relatively easy to do – just drop the unique constraint. If the primary key is the ssn this will be harder.
Define the field as auto_increment and mysql will handle it: