Why is a primary key an int?

We are used to having PKs in databases as integers.
The reason for this is that computers are good at numbers and an integer is a very versatile and fast number representation.

But there are drawbacks in the business layer.  A customerID can be compared to a orderID like so:

if( customerID == orderID ){…

This is not a good thing.

CustomerIDs should only be comparable to other CustomerIDs.
They should also not be addable, subtractable, multiplyable and being greater than anything else.  A CustomerID is equal or not equal to another CustomerID.  All other comparisions are not of this world.

I have yet to figure out how to implement this.

A comment of what to use as a primary key is found here.

Tags: , , ,

One Response to “Why is a primary key an int?”

  1. Anonymous says:

    I don’t agree.
    Int IS faster, that’s why primary keys should be int.
    There will be a performance hit with GUIDs in a large database.
    For no really smart reason, imho.
    You can’t always solve this kind of problem. What if the stupid junior programmer writes
    if (sessionId == txtCustomerId.Text)
    how would you avoid this kind of error in all situations, you don’t! Sometime when you write code you just have to know what you are doing! :) /Ola.L.

Leave a Reply