It's called College.
Posted
by jeffreyabecker
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by jeffreyabecker
Published on Mon, 27 Dec 2010 16:10:00 GMT
Indexed on
2010/12/27
16:54 UTC
Read the original article
Hit count: 404
SQL Server
Today I saw yet another 'GUID vs int as your primary key' article. Like most of the ones I've read this was filled with technical misrepresentations and out-right fallices. Chef's famous line that "There's a time and a place for everything children" applies here. GUIDs have distinct advantages and disadvantages which should be considered when choosing a data type for the primary key.
Fallacy 1: "Its easier"
An integer data type(tinyint, smallint, int, bigint) is a better artifical key than a GUID because its easier to remember.I'm a firm believer that your artifical primary keys should be opaque gibberish. PK's are an implementation detail which should never be exposed to the user or relied on for business logic. If you want things to come back in an order, add and ORDER BY clause and SortOrder fields. If you want a human-usable look-up add a business key with a unique constraint. If you want to know what order things were inserted into a table add a timestamp.
Fallacy 2: "Size Matters"
For many applications, the size of the artifical primary key is going to be irrelevant. The particular article which kicked this post off stated repeatedly that joining against an int has better performance than joining against a GUID. In computer science the performance of your algorithm is always a function of the number of data points. This still holds true for databases. Unless your table is very large, the performance difference between an int and a guid probably isnt going to be mesurable let alone noticeable. My personal experience is that the performance becomes an issue when you start having billions of rows in the table. At this point, you should probably start looking to move from int to bigint so the effective space/performance gain isnt as much as you'd think.GUID Advantages:
- Insert-ability / Mergeability: You can reliably insert guids into tables without key collisions.
- Database Independence: Saving entities to the database often requires knowing ids. With identity based ids the id must be selected back after every insert. GUIDs can be generated application-side allowing much faster inserts.
GUID Disadvantages:
- Generatability: You can calculate the next id for an integer pk pretty easily in your head but will need a program to generate GUIDs. Solution: "Select top 100 newid() from sysobjects"
- Fragmentation: most GUID generation algorithms generate pseudo random GUIDs. This can cause inserts into the middle of your clustered index. Solutions: add a default of newsequentialid() or use GuidComb in NHibernate.
© ASP.net Weblogs or respective owner