uniqueidentifier Data Type
The uniqueidentifier
data type stores a 16-byte globally unique identifier (GUID). A GUID is a unique number that is used to identify a process, an application, or a system. GUIDs are generated by the operating system.
Description
The uniqueidentifier
data type is useful for primary keys, and for storing transaction IDs. You can use the NEWID()
function to generate a new GUID.
Syntax
DECLARE @myGuid uniqueidentifier
SET @myGuid = NEWID()
PRINT @myGuid
Example Usage
Here is an example of how to create a table with a uniqueidentifier
column and insert a new GUID into it:
CREATE TABLE Products (
ProductID uniqueidentifier PRIMARY KEY DEFAULT NEWID(),
ProductName varchar(100) NOT NULL
);
INSERT INTO Products (ProductName)
VALUES ('Awesome Widget');
SELECT * FROM Products;
GUID Format
GUIDs are typically represented as a string of 32 hexadecimal digits, displayed in five groups separated by hyphens, in the format 8-4-4-4-12
. For example: A1B2C3D4-E5F6-7890-1234-567890ABCDEF
.
Key Functions
NEWID()
: Generates a new unique identifier (GUID).NEWSEQUENTIALID()
: Generates a GUID that is larger than any previously generated GUID on the computer. This function can be useful for clustered primary keys.
Considerations
- When using
uniqueidentifier
as a primary key, consider the performance implications of random GUIDs versus sequential GUIDs, especially with large tables and clustered indexes.NEWSEQUENTIALID()
can help mitigate fragmentation issues. - Ensure that your application or client libraries correctly handle the conversion between the string representation of a GUID and the 16-byte binary format.
Note: The
uniqueidentifier
data type is a standard SQL Server data type and is widely used for ensuring uniqueness across distributed systems.
Important: While
NEWID()
generates a globally unique identifier, it does not guarantee sequential generation, which can impact index performance. For scenarios where insertion order is important for performance, consider NEWSEQUENTIALID()
.