Sequences in SQL server 2012 – Implementing,Managing, Performance

Today we will  learn a new feature in SQL server 2012 – Sequences

What is Sequence and Why do we need in a Relational database?

Sequence is a linear progression of any numeric value with a specified interval , well sequence is not a new concept for RDMS , Oracle has been using this feature for a while and SQL server manges to use the same concept with IDENTITY column and on the other side Oracle does not have the IDENTITY column feature

So what is the advantage of using Sequence Number over Identity columns ?

  • The application requires a number before the insert into the table is made.
  • The application requires sharing a single series of numbers between multiple tables or multiple columns within a table.
  • The application must restart the number series when a specified number is reached. For example, after assigning values 1 through 10, the application starts assigning values 1 through 10 again.
  • The application requires sequence values to be sorted by another field. The NEXT VALUE FOR function can apply the OVER clause to the function call. The OVER clause guarantees that the values returned are generated in the order of the OVER clause’s ORDER BY clause.
  • An application requires multiple numbers to be assigned at the same time. For example, an application needs to reserve five sequential numbers. Requesting identity values could result in gaps in the series if other processes were simultaneously issued numbers. Calling sp_sequence_get_range can retrieve several numbers in the sequence at once.
  • You need to change the specification of the sequence, such as the increment value.

How Sequence works ?

How to create Sequences in SQL Server 2012

create sequence

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

How to use sequence

 

 

 

 

 

 

 

 

 

 

 

 

 

Using Sequences

update [dbo].[product]

set ProductID = next value for [dbo].[Masterproductid]

select name,minimum_value,maximum_value,current_value

from sys.sequences

where name = ‘Masterproductid’

select max(ProductID) as productid from dbo.product

TSQL

CREATE SEQUENCE [schema_name . ] sequence_name
[ AS [ built_in_integer_type | user-defined_integer_type ] ]
[ START WITH <constant> ]
[ INCREMENT BY <constant> ]
[ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
[ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
[ CYCLE | { NO CYCLE } ]
[ { CACHE [ <constant> ] } | { NO CACHE } ]
[ ; ]

Performance sequences

 

 

 

 

 

 

 

 

 

Limitations

  • Unlike identity columns, whose values cannot be changed, sequence values are not automatically protected after insertion into the table. To prevent sequence values from being changed, use an update trigger on the table to roll back changes.
  • Uniqueness is not automatically enforced for sequence values. The ability to reuse sequence values is by design. If sequence values in a table are required to be unique, create a unique index on the column. If sequence values in a table are required to be unique throughout a group of tables, create triggers to prevent duplicates caused by update statements or sequence number cycling.
  • The sequence object generates numbers according to its definition, but the sequence object does not control how the numbers are used. Sequence numbers inserted into a table can have gaps when a transaction is rolled back, when a sequence object is shared by multiple tables, or when sequence numbers are allocated without using them in tables. When created with the CACHE option, an unexpected shutdown, such as a power failure, can lose the sequence numbers in the cache.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

code

–@ SQL JUNKEI SHARE
–TABLE TO TEST THE PERFORMANCE OF SEQUENCES
CREATE TABLE [dbo].[SEQUENCEPRODUCT](
[ProductID] [int] NULL,
[Name] [nvarchar](50) NULL,

) ON [PRIMARY]

GO

ALTER TABLE [dbo].

[SEQUENCEPRODUCT] ADD CONSTRAINT [DEFSEQFORPRODUCT1] DEFAULT (NEXT VALUE FOR [MASTERPRODUCTID]) FOR [ProductID]
GO

ALTER SEQUENCE MASTERPRODUCTID

RESTART WITH 1;

–TABLE TO TEST PERFORMNACE OF IDENTITY
CREATE TABLE [dbo].[IDENTPRODUCT](
[ProductID] INT IDENTITY (1,1) ,
[Name] [nvarchar](50) NULL,

) ON [PRIMARY]

GO
CREATE TABLE SOURCEPRODUCT (NAME NVARCHAR(50))
–INSERT TEST DATA

GO
CREATE PROCEDURE INSERTIDENT
AS
BEGIN
INSERT INTO IDENTPRODUCT(NAME)
SELECT NAME FROM SOURCEPRODUCT
END
GO
CREATE PROCEDURE INSERTSEQUENCE
AS
BEGIN
INSERT INTO SEQUENCEPRODUCT(NAME)
SELECT NAME FROM SOURCEPRODUCT
END

SELECT COUNT(*) AS ‘NUMBER OF TEST ROWS’ FROM SOURCEPRODUCT
–4943950
DECLARE @STARTTIME DATETIME = GETDATE()
EXEC INSERTIDENT
SELECT DATEDIFF(SS,@STARTTIME,GETDATE()) AS ‘ENDTIME IDENTITY’
GO
DECLARE @STARTTIME DATETIME = GETDATE()
EXEC INSERTSEQUENCE
SELECT DATEDIFF(SS,@STARTTIME,GETDATE()) ‘ENDTIME SEQUENCE’
GO

— USING IN INSERT STATEMENT
INSERT INTO PRODUCT (PRODUCTID,NAME)

VALUES (NEXT VALUE FOR DBO.MASTERPRODUCTID,’TV’)
–USING IN SELECT WITH ORDER CLAUSE
SELECT NEXT VALUE FOR DBO.MASTERPRODUCTID OVER (ORDER BY NAME) AS ORDERPROD

FROM PRODUCT

–USING IN UPDATE
UPDATE DBO.PRODUCT

SET PRODUCTID = NEXT VALUE FOR DBO.MASTERPRODUCTID
–SEQUENCE IN TRANSACTIONS
—NO EFFECT ON SEQUENCE LIKE IDENTITY
SELECT CURRENT_VALUE FROM SYS.SEQUENCES WHERE NAME = ‘MASTERPRODUCTID’

BEGIN TRAN

INSERT INTO PRODUCT (PRODUCTID,NAME)

VALUES (NEXT VALUE FOR DBO.MASTERPRODUCTID,’TV’)
ROLLBACK TRAN

SELECT CURRENT_VALUE FROM SYS.SEQUENCES WHERE NAME = ‘MASTERPRODUCTID’

SELECT NAME FROM PRODUCT WHERE NAME = ‘TV’
–SQL JUNKIE SHARE

— REPLACING THE IDENTITY WITH SEQUENCES BY MODIFYING THE DEFAULT CONSTRAINT

—-CHECK CURRENT MAX VALUE IN PRODUCTS TABLE

SELECT MAX(PRODUCTID) AS MAXPRODUCTID FROM PRODUCT

— CURRENT VALUE FOR THE SEQUENCE

SELECT CURRENT_VALUE ‘BEFORE INSERT’ FROM SYS.SEQUENCES WHERE NAME =’MASTERPRODUCTID’
–MODIFY THE SEQUENCE TO STRAT FROM 504

ALTER SEQUENCE MASTERPRODUCTID

RESTART WITH 505;

–CHECK THE CURRENT VALUE FOR SEQUENCE

SELECT CURRENT_VALUE FROM SYS.SEQUENCES WHERE NAME =’MASTERPRODUCTID’

— MODIFY THE TABLE FOR DEFAULT CONSTRAINT

ALTER TABLE PRODUCT

ADD CONSTRAINT DEFSEQFORPRODUCT DEFAULT (NEXT VALUE FOR MASTERPRODUCTID) FOR PRODUCTID

–TEST IT BY INSERTING A VALUE
INSERT INTO PRODUCT (NAME)

VALUES (‘FOO’)

–CHECK PRODUCT AND SEQUENCES

SELECT PRODUCTID AS ‘PRODUCT ID AFTER INSERT’ FROM PRODUCT WHERE NAME = ‘FOO’

SELECT CURRENT_VALUE AS ‘CURRENTVALUE AFTER INSERT IN PRODUCT’ FROM SYS.SEQUENCES WHERE NAME =’MASTERPRODUCTID’

Advertisements

3 thoughts on “Sequences in SQL server 2012 – Implementing,Managing, Performance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s