T-SQL features in SQL Server 2012 – CREATE SEQUENCE

A common feature in table design is to place an auto incrementing number on a field in the form of an IDENTITY column. So this is an easy way of maintaining a sequential number on a table.

What if you wanted to create a database wide identity? Prior to SQL 2012, you might choose to do it by having a table sitting there in the middle of it all with a numeric field which gets updated by some function every time a new identity is created. CREATE SEQUENCE takes away this overhead.

T-SQL then by default a sequence is created as a BIGINT datatype unless you specify otherwise, for example:

CREATE SEQUENCE MyDemoSequence AS SMALLINT
 START WITH 1
 INCREMENT BY 1;

Note that START, INCREMENT, MINVALUE and MAXVALUE must be configured within the boundaries of the data type. For example, you couldn’t specify a negative START value for a TINYINT data type.

To use CREATE SEQUENCETo get the next value in the sequence use the NEXT VALUE FOR

SELECT NEXT VALUE FOR MyDemoSequence;

If you were inserting to a table, it would like something like this:

INSERT INTO YourTable(ID, Name)VALUES(NEXT VALUE FOR MyDemoSequence, ‘Your name’);

To know about CREATE SEQUENCE

CYCLE and NO CYCLE tells the sequence to cycle back round to the minimum value when the last value has been allocated in the sequence. By default, this is set to NO CYCLE.

CACHE or NO CACHE, designed for performance benefits in reducing IO requests for new numbers out of a sequence. A cache value can be specified and the numbers up to the maximum cache value are loaded up into memory until the cache is exceeded and a new set of numbers is required.

For example, you might create a sequence with a cache of 20. When a value is needed from the sequence, the minimum value in the sequence up to and including the CACHE value are loaded into memory. The CACHE value of 20 is written to the system table sys.sequences and when 20 gets used and 21 is requested, then a fresh set of numbers is allocated to the cache (21-40) with 40 being written to the sys.sequences table as the CACHE value.

Here’s an example of a sequence created using CYCLE and CACHE

CREATE SEQUENCE MyDemoSequence AS INTSTART WITH 1INCREMENT BY 1CACHE 20CYCLE;

Lets have a quick look at the sys.sequences table:

SELECT cache_size, is_cached, current_value
FROM sys.sequences
WHERE name = ‘MyDemoSequence’;

The return values will be:
cache_size  = 20
is_cached = 1
current_value = 1