SQL SERVER

How to check GUID(Globally Unique Identifier) is null or empty in SQL Server

GUID(Globally Unique Identifier) is null or empty in SQL Server

A GUID in SQL Server can generate unique IDs with the least probability of the exact ID being generated and/or used by someone else coincidently.

Before we dive into understanding the way of generating GUIDs in SQL Server, it’s necessary to understand some important concepts about GUID itself. So, let’s understand GUID conceptually.

  • Unique Identifiers are broadly defined by two acronyms – GUID (Globally Unique Identifier) and UUID (Universally Unique Identifier). Both represent the same thing – unique IDs that are unique across space and time.
  • The specification and the methodology of generating GUIDs is defined by IETF and the specification is known as RFC4122.
  • GUIDs can be generated in multiple ways. The most common ones are based on Random number generation, Time clock sequence, Hardware based using MAC addressed of network cards, and Content based by calculating hash of the data using common hashing algorithms like MD5, AES, SHA and others.
  • GUIDs are typically 128-bit in size and 32 digits long in the pattern of 8 digits – 4 digits – 4 digits – 4 digits – 12 digits
  • Using the above mechanism, a total of approximately 1038 GUIDs can be generated, which are more than enough for everyone in the world to use GUIDs for trillions of data items per person.

Now that we have enough understanding of GUIDs, we can start focusing on the methods of creating GUIDs in SQL Server. There are two functions using which you can create GUIDs in SQL Server – NewID and NewSequentialID. And there’s a data type – “uniqueidentifier” which can be used to store GUIDs. It stores a 16-btye binary value.

SQL Server NEWID to Generate GUID

Let’s create a variable of uniqueidentifier data type.  Type the below code in SSMS and execute.

DECLARE @guid uniqueidentifier = NEWID();
SELECT @guid as 'GUID';			

Here we created a variable named guid of data type uniqueidentifier. To generate a unique identifier, we need to assign a default method of creating it, and for that we have used the NEWID function which generates and returns a RFC4122 compliant GUID. The output of the above code would be as shown below. This would be different when you execute it on your machine, as the GUIDs are supposed to be globally unique at any given point in time. In fact, I executed the same code twice and each time the ID that came out was different as expected. This is the entire purpose of generating GUIDs.

Sample GUID in SQL Server
Sample GUID in SQL Server

While creating a new table, you can create a field of uniqueidentifer data type as assign the NEWID as the default function as shown below.

CREATE TABLE Product_A
(
ID uniqueidentifier default newid(),
productname varchar(50)
)			

Insert some records into this table using the below code.

Insert Into Product_A(productname) values('A1')
Insert Into Product_A(productname) values('A2')
Insert Into Product_A(productname) values('A3')
Select * from Product_A			

The output would be as shown below.

GUID values in SQL Server

One thing to note is regarding different operations that you can perform on GUIDs / uniqueidentifier data type. If you sort the ID field in the above table, the result is as shown below in my case. The IDs generated are not necessarily in increasing order, so if you sort the data by GUIDs, the data may not be in the same order in which you inserted. SQL Server sorts GUIDs typically from the 5th part of the GUID towards the 1st part, and the search algorithm is not well documented. The NewID function used randomness (random activity) as part of its GUID generation mechanism, so it cannot be guaranteed that every GUID that is generated would be in sequence or in order of higher values.

SELECT * FROM Table with GUIDs in SQL Server

Also, only comparison operators are supported on GUIDs. For example, if you attempt to use an aggregation operator like sum, you would encounter an error as shown below.

Unable to SUM GUIDs in SQL Server - results in an error
Declare @MyGuid Uniqueidentifier


If(@MyGuid IS NULL)
Begin
     Print ‘Guid is null’
End
Else
Begin
     Print ‘Guid is not null’
End



In the above example, since @MyGuid is just declared and not initialised, it prints the message “Guid is null”

Now let’s say, if a GUID variable is NULL, then we want to initialise that GUID variable with a new GUID value. If it’s not NULL, then we want to retain it’s value. One way to do this is by using an IF condition as shown below.

Declare @MyGuid UniqueIdentifier


If(@MyGuid IS NULL)
Begin
     Set @MyGuid = NEWID()
End


Select @MyGuid

We can achieve exactly the same thing by using ISNULL() function. The advantage of using ISNULL() function is that, it reduces the amount of code we have to write.

Declare @MyGuid UniqueIdentifier
Select ISNULL(@MyGuid, NewID())

How to check if a GUID is EMPTY : Before understanding how to check if a GUID is empty, let’s understand what is an empty GUID. An empty GUID is a GUID with all ZEROS as shown below.
00000000-0000-0000-0000-000000000000

How to create this empty GUID. Do we have to type all the ZERO’s and Hyphens. The answe is NO. We do not have to type them manually. Instead use one of the following SELECT query’s to create an empty GUID. I prefer to use the second SELECT statement as it has only one CAST

SELECT CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
OR
SELECT CAST(0x0 AS UNIQUEIDENTIFIER)

To check if a GUID is an empty GUID, you have 2 options
Option 1: You can compare it to an Empty GUID value as shown below

Declare @MyGuid UniqueIdentifier
Set @MyGuid = ‘00000000-0000-0000-0000-000000000000’


If(@MyGuid = ‘00000000-0000-0000-0000-000000000000’)
Begin
     Print ‘Guid is Empty’
End
Else
Begin
     Print ‘Guid is not Empty’
End

Option 2: You can also compare it to a return value of the CAST method

Declare @MyGuid UniqueIdentifier
Set @MyGuid = ‘00000000-0000-0000-0000-000000000000’


If(@MyGuid = Cast(0x0 as Uniqueidentifier))
Begin
     Print ‘Guid is Empty’
End
Else
Begin
     Print ‘Guid is not Empty’
End

About the author

shohal

1 Comment

Leave a Comment