tags:

views:

2286

answers:

4

I need a simple table with a user name and password field in mySQL. Since user names must be unique, it makes sense to me to make them the primary key.

Is it better to use CHAR() or VARCHAR() as a primary key?

+8  A: 

may as well just use a user ID index, it's much faster for joins vs char/varchar. the two seconds it takes to add that now could save you a lot of time later if you accidently have to expand the functionality of your schema.

some pitfalls to think about:

  • say we add a few tables at a future date, what if someone wants to change a username?
  • say the app is more successful then we think, and we have to look at optimization, do you really want to redo your schema at this point to reduce the overhead of a varchar'ed index?
Owen
Agreed, you probably want a user id for something and it's a whole lot smaller than storing a username in any joined tables.
Darryl Hein
A: 

I don't see CHAR used much in any MySQL databases i've worked on. I would go with the VARCHAR

For a CHAR(30) for example, the entire 30 characters are stored in the table meaning every entry will take up the same space, even if your username is only 10 characters long.

Using VARCHAR(30) it will only use enough space to store the string you have entered.

On a small table it wont make much difference, but on a larger table the VARCHAR should prove to keep it smaller overall.

Jarod Elliott
In this case I think CHAR makes more sense. It's a fixed length field. If all the fields in the table are fixed length, the query will run faster as mysql must not calculate where the next records start. Nowdays space is cheap, I'll trade a bit of space here for more speed.
DreamWerx
just watch out for the trailing spaces on CHAR when matching against a string
Steve Tranby
+4  A: 

I would work hard to NOT use CHAR() or VARCHAR() as a PK but use an int with an auto_increment instead. This allows you to use that user_id in child tables if needed and queries on the PK should be faster. If you have to use either a CHAR() or VARCHAR(), I'd go with the CHAR() since it's a fixed width.

I'm not 100% sure how MySQL deals with VARCHAR()'s but most database engines have to do some magic under the hood to help the engine know where the VARCHAR() fields ends and where the next field begins, a CHAR() makes it straight forward and keeps the engine from having to think to much.

DL Redden
+2  A: 

[I would work hard to NOT use CHAR() or VARCHAR() as a PK but use an int with an auto_increment instead.] +1

Put a unique constraint of the username but use the int field as the PK

RhysC