Integer or character primary key

I have a table with a primary key (PK), which was naturally defined as an integer number from my business model. Do I have to keep this PK as an integer or could I use a char/varchar data type? Considering that the values for PK will not be greater than 500000, using varchar(6) could save some space. Does it affect indexing or querying?

    Requires Free Membership to View

It's not terribly clear what "naturally defined" means, but if it's an existing number scheme already in use, you should definitely use it rather than some arbitrary autonumber or identity column. You are probably not referring to the whole "natural versus surrogate" debate anyway.

As for whether to use INTEGER or VARCHAR, use INTEGER. Integer operations (indexing, sorting, comparing) are, in general, faster than character. And an INTEGER column requires only 4 bytes, even for numbers as large as 2 billion, so you may save some space (if a good portion of the numbers actually require more than 4 digits).

Finally, there is the issue of sorting, which becomes clear when you sort VARCHAR values and get a result like this:

1
12
131
2
3
34
37
9
937

This is obviously not very useful if in fact you wanted numerical order.


This was first published in August 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.