Wednesday, 30 January 2013

GUID : In SQL Database


At times we GUIDs as primary key for tables.Is it a good idea to use GUIDs asPK in tables.

According to me you should avoid going with GUID as PK in a SQL table.
using a GUID as a primary column is not a good idea.
You normally have the clustered index based on the primary column, guids will give you a random generation of codes so SQL server will end up sorting a lot of data at each insertion. Rather consider using identity column for primary key, they are created serially and don't require sorting.

GUIDs often cause performance issues , many people don't prefer GUIDs beacuse they are hard to play with ,cause the indexes to bloat to a bigger size .


If this is the problem, then why should we create a GUID at all?

GUIDs are unique numbers and they never get repeated ,if you have scenarios where you often need to sync data between users , or have a smart client app or are using a replication scenario then it is always preffered or a best practice  to have a GUID column as when the data is merged across ,its not going to cause issues with duplicate PKs.

In case you want to use GUIDs following can help you start with

a. To create a table with a GUID column use something like following

CREATE
 TABLE TestTable

(TestGUIDColumn UNIQUEIDENTIFIER DEFAULT NEWID(),

SecondColumn
VARCHAR(MAX) )

b. To insert data on to the table

INSERT INTO TestTable (TestGUIDColumn , SecondColumn) vaues (NEWID(), 'Archita')

c. To sort the table by GUID

Select TestGUIDColumn  , SecondColumn FROM TestTable
ORDER BY TestGUIDColumn 

You may agree or disagree with me  ,please write to me with your views.

No comments:

Post a Comment