How do you use the NEWID and NEWSEQUENTIALID functions to generate unique identifier values in SQL Server?
Posted by KarenKg
Last Updated: June 28, 2024
In SQL Server, the NEWID() and NEWSEQUENTIALID() functions are used to generate unique identifier (GUID) values. Both functions are useful for generating unique values that can be used as primary keys or unique identifiers in your tables. However, they work in slightly different ways.
NEWID Function
The NEWID() function generates a globally unique identifier (GUID) that is random. Here's how you can use it: 1. Basic Usage in a SELECT Statement:
SELECT NEWID() AS UniqueIdentifier;
2. Using NEWID() in a Table: When you create a table, you can set a column to use NEWID() to automatically generate a unique value:
CREATE TABLE MyTable (
       ID UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY,
       Name NVARCHAR(100)
   );
Inserting data into MyTable does not require specifying the ID column:
INSERT INTO MyTable (Name) VALUES ('Sample Name');
The ID column will automatically be filled with a unique value generated by NEWID().
NEWSEQUENTIALID Function
The NEWSEQUENTIALID() function, on the other hand, generates a GUID that is unique and sequential, which can help reduce fragmentation in indexes compared to NEWID(). This is particularly useful in situations where a lot of inserts occur. However, it's worth noting that NEWSEQUENTIALID() is only available as a default value for a column and cannot be called in a SELECT statement directly. 1. Using NEWSEQUENTIALID() in a Table: Here’s how to create a table that uses NEWSEQUENTIALID():
CREATE TABLE MySequentialTable (
       ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
       Name NVARCHAR(100)
   );
Just like with NEWID(), you can insert data without specifying the ID:
INSERT INTO MySequentialTable (Name) VALUES ('Sample Name');
The ID column will be filled with a unique, sequential value generated by NEWSEQUENTIALID().
Summary
- Use NEWID() when you need a completely random GUID. - Use NEWSEQUENTIALID() when you want a GUID that reduces fragmentation and is sequential, making it more efficient for insert-heavy scenarios.
Notes
- When defining columns with these functions, remember that both return values of type UNIQUEIDENTIFIER, so the column should be defined as such. - GUIDs are quite large (16 bytes), so consider performance implications when using them as primary keys in large tables.