There are many applications that require incremental numbers for maintaining unique rows in a table. For several years, we’ve been using IDENTITY() column as our primary option to generate incremental numbers for unique records or for Primary key values and it has been the first choice for developers. You’ve tried IDENTITY() and now try the new feature introduced in SQL Server 2012 and experience the difference.

SQL Server introduces a brand new schema bound object called SEQUENCE. Sequence generates numeric values based on the specification of a SEQUENCE object. You can generate numeric values in either ascending or descending order and they can be independent of tables unlike IDENTITY columns.

Here’s the syntax on how you can create a SEQUENCE using various options.

Lets now take a look at an example on how to use SEQUENCE in SQL Server.

We will look at:

  1. Creating a sequence
  2. Create a sample Item table
  3. Use Sequence while inserting data
  4. Query the table
  5. Reset Sequence values
  6. Alter or Delete Sequence values

Step 1: In this step, we will create a new object called ItemIDSequence that will start with a value of 1 and increment it’s value by 1.

Step 2: In this step, we will create a sample ITEM table with just two columns.

Step 3: In this step, we will insert data in the ITEM table using ItemIDSequence which will automatically insert and increment the values of ItemIDSequence by 1.

Step 4: In this step, we will query the ITEM table to review the data in the ITEM table. Notice that the ITEMNO column in the ITEM table has sequential numbers that were auto-inserted using ItemIDSequence.

You can Alter, Delete or Query any sequence using the below examples:

Important and Best Practices for Sequence:

  1. Sequence values are not automatically protected after insertion into a table. You should use Update Trigger on a table to prevent sequence values from being changed.
  2. Sequence does not automatically enforce uniqueness for sequence values. You should create unique index on the sequence column to enforce uniqueness.
  3. If you have created a sequence (Example: 1 through 100) and if the rows in the table grows beyond 100 rows, SQL Server would start assigning values 1 through 100 again.
  4. By default, if you do not specify data type for a sequence, BIGINT data type is used. (Note: you can create sequence of any integer data type)