How to use and features of MSSQL NEWID() function

The NEWID() function is a function used to generate a unique identifier (GUID) in MSSQL.

NEWID() function features

  • The GUID generated by the NEWID() function returns a random value that is not duplicated each time it is called.
  • The NEWID() function is compatible with RFC4122. That is, the return value is a random value that is not duplicated.
  • NEWID() is a Uniqueidentity type function in 32 hex code.

How to use NEWID() function

How to use NEWID() in the SELECT clause.

  • Here is a basic source example.
--1.How to use NEWID() in the SELECT clause.
SELECT  NEWID()  AS 'NewId'  ;

How to use NEWID() when creating a table.

  • The NEWID() function can be used to insert an arbitrary value when entering data as the default value for a column.
-- 2. How to use NEWID() when creating a table.
DROP TABLE IF EXISTS InfoForIdentity;
CREATE TABLE InfoForIdentity (
    NewIdKey uniqueidentifier NOT NULL DEFAULT NEWID(),
    UserId varchar(255)   
);
 
INSERT INTO InfoForIdentity (UserId)
VALUES  (1001),(1002),(1003),(1004),(1005);

SELECT UserId, NewIdKey
  FROM InfoForIdentity;

How to use data types and variables.

  • The data type must be declared as uniqueidentifier to be used.
  • Keep running NEWID() to check if there are any duplicate values.
-- 3. How to use data types and variables.
DECLARE @NewIdKey uniqueidentifier ;  
SET @NewIdKey = NEWID();  
SELECT @NewIdKey;

Sort randomly using NEWID().

  • Here is an example of using the newid() function in order by.
-- 4. Sorting randomly using NEWID()
DROP TABLE IF EXISTS InfoForIdentityRandom;
CREATE TABLE InfoForIdentityRandom (
    UserId  int,
    UserNm varchar(255)  
) ON [PRIMARY];
INSERT INTO dbo.InfoForIdentityRandom(UserId,UserNm) VALUES
(1, N'Ken'),(2, N'Brian'),(3, N'Stephen'),(4, N'Michael'),(5, N'Linda');

SELECT TOP 10 *
FROM InfoForIdentityRandom
ORDER BY NEWID();

Convert NEWID() to varchar type.

  • UNIQUEIDENTIFIER type can be converted to string type using varchar or cast.
-- Convert NEWID() to varchar type
DECLARE @IdentityToString UNIQUEIDENTIFIER = NEWID()
SELECT CAST(@IdentityToString AS VARCHAR(50))
SELECT CONVERT(VARCHAR(50),@IdentityToString)
SELECT @IdentityToString;

features of MSSQL NEWID() function

NEWID() function duplicated

  • If you are concerned about duplication, you can also create a unique index on that date.

Categories:

Updated:

Leave a comment