Sequence objects are used to sequentially generate numeric values. They were introduced in SQL Server 2012.
Sequence objects are similar to the IDENTITY column in any SQL table. However, unlike the IDENTITY column, they are independent and are not attached to any table. Sequence objects are used both independently and within the DML statements i.e. INSERT, UPDATE and DELETE.
This article will take a detailed look at sequence objects.
Syntax
The syntax for a Sequence object is as follows:
1 2 3 4 5 6 7 8 |
CREATE SEQUENCE [schema].[Name_of_Sequence] [ AS <data type> ] [ START WITH <value> ] [ INCREMENT BY <value> ] [ MINVALUE <value > | NO MINVALUE ] [ MAXVALUE <value> | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; |
The syntax works as follows:
Parameter | Description |
CREATE SEQUENCE | Used to create a sequence followed by a database schema and the name of the sequence |
AS |
Specifies the data type of the sequence.
Data types can be Decimal, Int, SmallInt, TinyInt, and BigInt. The default value for the data type is BigInt |
START WITH | Sets the starting value for the sequence object |
INCREMENT BY | Sets the amount that you want your sequence object to increment by |
MIN VALUE | This is an optional parameter that specifies the minimum value for the sequence object |
MAX VALUE | This is an optional parameter that sets the maximum value for the sequence object |
CYCLE |
This specifies if the sequence object should be restarted once it has reached its maximum or minimum value.
It is an optional parameter for which the default value is NO CYCLE |
CACHE |
This is used to cache sequence object values.
It is also optional parameter with the default value of NO CACHE |
A Simple Example
Let’s take a look at a simple example of a sequence object. Execute the following script:
1 2 3 4 |
CREATE SEQUENCE [dbo].[NewCounter] AS INT START WITH 5 INCREMENT BY 5 |
In the script, we create a sequence object named NewCounter. The type of this sequence object is integer; it starts from 5 and increments by 5.
To see what our NewCounter sequence object contains, execute the following script:
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter] |
When you execute the above script for the first time, you will see ‘5’ in the output. As shown below. This is the start value for the counter.
The “NEXT VALUE FOR” statement basically increments the counter.
Execute the following script again:
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter] |
This time you will see ‘10’ in the output. Each time you execute the above script, the value for the NewCounter sequence will be incremented by 5.
Retrieving Sequence Object Details
To retrieve the details of our newly created sequence, execute the following script:
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter] |
The script above retrieves all the details of the sequence object such as name, minimum value, maximum value, cycled or not, cached or not, current value, date creation etc. The output of the script above looks like this:
Altering a Sequence
To modify an existing sequence, the ALTER SEQUENCE statement is used. Have a look at the script below:
1 2 |
ALTER SEQUENCE [NewCounter] RESTART WITH 7 |
The above script will modify the existing sequence object ‘NewCounter’ by updating its starting value to 7.
Now if you execute the following statement:
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter] |
You will see ‘7’ in the output.
Executing the above statement again will return 12 (7+5). This is because we only updated the starting value, the value for INCREMENT BY remains same, therefore 7 plus the increment value 5 will be equal to 12.
Using Sequence Object with INSERT
Sequence objects can be used in combination with INSERT statements to insert values in a sequential manner. For instance, sequence object can be used to insert values for the primary key column.
Let’s create a simple table Students table with three columns Id, StudentName and StudentAge. We will use sequence object to insert a value in the Id column whenever a new record is inserted into the table.
Let’s create a table:
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE DATABASE School GO USE School GO CREATE TABLE Students ( Id INT PRIMARY KEY, StudentName VARCHAR (50), StudentAge INT ) |
Next, we will create a sequence object with an initial value of 1. We will increment this counter by 1. Execute the following script to create such a sequence object, which we’ve called IdCounter.
1 2 3 4 |
CREATE SEQUENCE [dbo].[IdCounter] AS INT START WITH 1 INCREMENT BY 1 |
Now let’s insert some records in the Students table that we just created. For the Id column of the table we will use the following statement:
1 |
NEXT VALUE FOR [dbo].[IdCounter] |
The above statement will fetch the next value for the IdCounter sequence object and will insert it into the Students table. The script for inserting records into Students table is as follows:
1 2 3 4 5 6 |
USE School INSERT INTO Students VALUES (NEXT VALUE FOR [dbo].[IdCounter], 'Sally', 20 ) INSERT INTO Students VALUES (NEXT VALUE FOR [dbo].[IdCounter],'Edward', 36 ) INSERT INTO Students VALUES (NEXT VALUE FOR [dbo].[IdCounter],'Jon', 35) INSERT INTO Students VALUES (NEXT VALUE FOR [dbo].[IdCounter],'Scot', 41 ) INSERT INTO Students VALUES (NEXT VALUE FOR [dbo].[IdCounter],'Ben', 35 ) |
Select all the records from the Students table, execute the following script:
1 |
SELECT * FROM Students |
The output looks like this:
You can see from the output that the Id column contains values from 1 to 5 as provided by the IdCounter sequence object.
Decrementing a Sequence Object
To decrement sequence, set the value for INCREMENT BY to a negative number. Setting INCREMENT BY to -1 decrements the sequence object by 1.
1 2 3 4 |
CREATE SEQUENCE [dbo].[NewCounter2] AS INT START WITH 10 INCREMENT BY -1 |
Now execute the following script twice:
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter2] |
You will see 9 in the output. This is because the first time you execute the command above, the value of NewCounter2 sequence object is initialized to 10. Executing the script again decrements it by 1 to 9.
Setting the Min and Max Value for Sequence Objects
You can set the minimum and maximum value that your sequence object can reach. If you try to increment or decrement a sequence object beyond the maximum or minimum values, an exception is thrown.
1 2 3 4 5 6 |
CREATE SEQUENCE [dbo].[NewCounter4] AS INT START WITH 10 INCREMENT BY 10 MINVALUE 10 MAXVALUE 50 |
In the script above, we create a sequence object named ‘NewCounter4’. It has a starting value as well as increment of 10. The minimum value for this sequence object is 10 while the maximum value is 50.
Now if you increment the value of this sequence object beyond 50, an error will be thrown. For instance, executing the script 6 times attempts to set the value of the sequence object NewCounter4 to 60. The maximum value for the sequence object is set at 50, and so an error will be thrown.
1 |
SELECT NEXT VALUE FOR [dbo].[NewCounter4] |
The screenshot for the error is as follows:
Incrementing/Decrementing Sequence Objects in Cycle
We saw that when we tried to increment a sequence object beyond its maximum value, an error was thrown. You can use a CYCLE flag to avoid this error. If a CYCLE flag for a sequence is set to true, the value for the sequence object is again set to its starting value , whenever you try to increment or decrement its value beyond the maximum or minimum value.
This is best explained with the help of an example.
1 2 3 4 5 6 7 |
CREATE SEQUENCE [dbo].[NewCounter7] AS INT START WITH 10 INCREMENT BY 10 MINVALUE 10 MAXVALUE 50 CYCLE |
Now, if you try to increment the value of the sequence object NewCounter7 6 times, the value of the sequence object will be incremented to 60. This is greater than the maximum value 50. In this case the value of the NewCounter7 will be again set to starting value i.e. 10.
Other great articles from Ben
Understanding the GUID data type in SQL Server |
Sequence Objects in SQL Server |
- Working with the SQL MIN function in SQL Server - May 12, 2022
- SQL percentage calculation examples in SQL Server - January 19, 2022
- Working with Power BI report themes - February 25, 2021