SQL Server UNIQUEIDENTIFIER Data Type

In SQL Server, UNIQUEIDENTIFIER is a data type used to store a globally unique identifier (GUID). A GUID is a binary value generated by an algorithm, typically used as a unique identifier in distributed systems. This data type occupies 16 bytes and has a storage range of 0-2^128-1.

Syntax

The syntax for the UNIQUEIDENTIFIER data type is as follows:

UNIQUEIDENTIFIER

Use cases

The UNIQUEIDENTIFIER data type is primarily used in scenarios where a unique identifier needs to be generated, such as data synchronization, replication, and merging in distributed systems. It can also be used to store unique identifiers in a database, for example when creating a primary key in a table.

Examples

Example 1: Creating a table with the UNIQUEIDENTIFIER data type

CREATE TABLE Persons (
    PersonID UNIQUEIDENTIFIER PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50)
);

Example 2: Inserting data of the UNIQUEIDENTIFIER data type

INSERT INTO Persons (PersonID, FirstName, LastName)
VALUES ('6F9619FF-8B86-D011-B42D-00C04FC964FF', 'John', 'Doe');

Conclusion

The UNIQUEIDENTIFIER data type is useful for storing unique identifiers in scenarios where they need to be generated or stored in a database. Although it occupies more storage space than other data types, it ensures the uniqueness of data and avoids issues with data conflicts.