NEWID

Returns a uniqueidentifier value that is guaranteed to be unique across space and time. A uniqueidentifier is a 16-byte binary object that can be used for primary keys, foreign keys, and data warehouse keys.

Syntax

NEWID ( )

Description

The NEWID function generates a new globally unique identifier (GUID) value. Each call to NEWID generates a new GUID. The generated GUIDs are unique across all computers and all times. This function is useful for creating primary keys that are guaranteed to be unique or for generating unique values for various purposes within your database.

The uniqueidentifier data type can store GUIDs. GUIDs are 128-bit integers that are unique. You can use NEWID to generate these values.

Return Value

uniqueidentifier

The value returned by NEWID is a new GUID.

Examples

Example 1: Generating a new GUID

This example shows how to generate a new GUID and assign it to a variable.

DECLARE @MyGuid uniqueidentifier;
SET @MyGuid = NEWID();
SELECT @MyGuid AS GeneratedGUID;

Example 2: Inserting a new GUID into a table

This example shows how to use NEWID to insert a new unique identifier into a table's primary key column.

First, let's assume you have a table named Product with a ProductID column of type uniqueidentifier, set with a default value of NEWID().

-- Assuming Product table with ProductID uniqueidentifier DEFAULT NEWID()
INSERT INTO Product (ProductName, Price)
VALUES ('Super Widget', 19.99);

-- To see the generated ID
SELECT TOP 1 ProductID, ProductName FROM Product ORDER BY ProductID DESC;

Example 3: Using NEWID in a WHERE clause (less common, but illustrates usage)

This example demonstrates using NEWID() within a query, although typically it's used for data insertion or generation.

-- This is illustrative; usually you'd compare against an existing GUID.
SELECT *
FROM YourTable
WHERE SomeGuidColumn = NEWID(); -- This will likely return no rows as NEWID() generates a new value each time.

See Also