NEWID (Transact-SQL)
Returns a uniqueidentifier
value that is guaranteed to be unique across all computers and all times. A uniqueidentifier
is a 16-byte GUID.
Syntax
NEWID ( )
Return Value
Returns a uniqueidentifier
value.
Description
The NEWID
function generates a new globally unique identifier (GUID) for each row returned in a query result set. If you need to generate a GUID within your application code, use the Guid.NewGuid()
method in the .NET Framework.
The GUID generated by NEWID
is a version 4 UUID, which means it's a randomly generated GUID.
Examples
A. Creating a table with a default uniqueidentifier column
The following example creates a table with a uniqueidentifier
column named ID
. The NEWID()
function is used as the default value for the ID
column. This means that when a new row is inserted without specifying a value for ID
, a new GUID is automatically generated.
CREATE TABLE MyTable (
ID uniqueidentifier PRIMARY KEY DEFAULT NEWID(),
ProductName varchar(100) NOT NULL,
Price money
);
INSERT INTO MyTable (ProductName, Price) VALUES ('Laptop', 1200.00);
INSERT INTO MyTable (ProductName, Price) VALUES ('Keyboard', 75.00);
SELECT * FROM MyTable;
Output:
ID | ProductName | Price |
---|---|---|
A1B2C3D4-E5F6-7890-1234-567890ABCDEF | Laptop | 1200.00 |
F9E8D7C6-B5A4-3210-FEDC-BA9876543210 | Keyboard | 75.00 |
B. Generating a GUID within a query
The following example simply returns a new GUID without inserting it into a table.
SELECT NEWID() AS NewGUID;
Output (the GUID will vary):
NewGUID |
---|
00000000-1111-2222-3333-444444444444 |
Remarks
NEWID()
is an indeterministic function. Each timeNEWID()
is called in a query, it returns a different GUID.- The
NEWID()
function can be used inSELECT
,WHERE
, andORDER BY
clauses, as well as inDEFAULT
constraints. - For generating GUIDs in application code, consider using the
Guid.NewGuid()
method in the .NET Framework.