What Is Data Type Uniqueidentifier?

//

Larry Thompson

What Is Data Type Uniqueidentifier?

The uniqueidentifier data type in SQL Server represents a globally unique identifier (GUID). It is a 16-byte binary value that is generated using a combination of network card identification numbers, timestamp information, and random values. A uniqueidentifier value can be used to uniquely identify a row in a table or as a primary key in a database.

Benefits of Using Uniqueidentifier

The uniqueidentifier data type offers several benefits:

  • Universally Unique: As the name suggests, a uniqueidentifier is globally and universally unique. The probability of generating two identical uniqueidentifier values is extremely low, making it suitable for scenarios where uniqueness is critical.
  • Easy Integration: The uniqueidentifier data type can be easily integrated with other systems and databases since it follows the universally accepted GUID standard.
  • Flexibility: Unlike auto-incrementing integer values, uniqueidentifiers are not limited to sequential numbering. They can be generated independently and assigned as needed.

Syntax and Usage

To define a column with the uniqueidentifier data type in SQL Server, you can use the following syntax:


CREATE TABLE TableName
(
    ColumnName UNIQUEIDENTIFIER
)

To insert values into a column defined as uniqueidentifier, you can use either the NEWID() function or declare your own GUID value:


INSERT INTO TableName (ColumnName)
VALUES (NEWID())

DECLARE @GuidValue UNIQUEIDENTIFIER = 'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'
INSERT INTO TableName (ColumnName)
VALUES (@GuidValue)

Examples:

Here are a few examples to illustrate the usage of the uniqueidentifier data type:


CREATE TABLE Employees
(
    EmployeeID UNIQUEIDENTIFIER PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50)
)

DECLARE @NewEmployeeID UNIQUEIDENTIFIER = NEWID()
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (@NewEmployeeID, 'John', 'Doe')

In this example, a table named “Employees” is created with a column “EmployeeID” of type uniqueidentifier. The primary key constraint ensures that each employee ID is unique. A new employee is then inserted into the table with a randomly generated uniqueidentifier value.

Conclusion

The uniqueidentifier data type in SQL Server provides an excellent way to generate globally unique identifiers. It offers universality, ease of integration, and flexibility in various scenarios where uniqueness is crucial. By understanding its benefits and usage, you can effectively incorporate this data type into your database designs.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy