Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to store a GUID value in SQL Server database

Say, if I need to store non-repeating GUID values (something like {AB50C41E-3814-4533-8F68-A691B4DA9043}) in the SQL Server database, what is the most efficient way to define the column to store it? (i.e. as string, a blob, or convert it into a 16-byte integer.)

PS. The column must be defined as an INDEX and be UNIQUE.

like image 716
ahmd0 Avatar asked Dec 30 '11 05:12

ahmd0


People also ask

How do you store GUIDs in SQL?

There are two functions using which you can create GUIDs in SQL Server – NewID and NewSequentialID. And there's a data type – "uniqueidentifier" which can be used to store GUIDs. It stores a 16-btye binary value.

What are the best practices for using a GUID as a primary key specifically regarding performance?

GUIDs may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.

Is GUID good for primary key?

GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.

Which data type is used for assigning GUID value in SQL?

The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.


1 Answers

  • Use the uniqueidentifier data type which is designed for GUIDs
    For example, they will sort like GUIDs should
  • Create a UNIQUE index on it (more flexible than a unique constraint

Note, these are 2 separate steps

like image 85
gbn Avatar answered Sep 18 '22 15:09

gbn