Before continuing this blog post – please read the first part of the SEQUENCE Puzzle here A Puzzle – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value. Where we played a simple guessing game about predicting next value. The answers the of puzzle is shared on the blog posts as a comment. Now here is the next puzzle based on yesterday’s puzzle.
First execute the script which I have written here. The only difference between yesterday’s script is that I have removed the MINVALUE as 1 from the syntax. Now guess what will be the next value as requested in the query.
USE TempDB
GO
-- Create sequence
CREATE SEQUENCE dbo.SequenceID AS BIGINT
START WITH 3
INCREMENT BY 1
MAXVALUE 5
CYCLE
NO CACHE;
GO
-- Following will return 3
SELECT next value FOR dbo.SequenceID;
-- Following will return 4
SELECT next value FOR dbo.SequenceID;
-- Following will return 5
SELECT next value FOR dbo.SequenceID;
-- Following will return which number
SELECT next value FOR dbo.SequenceID;
-- Clean up
DROP SEQUENCE dbo.SequenceID;
GO
Above script gave me following resultset.
3 is the starting value and 5 is the maximum value. Once Sequence reaches to maximum value what happens? and WHY?
I (kindly) suggest you try to attempt to answer this question without running this code in SQL Server 2012. I am very confident that irrespective of SQL Server version you are running you will have great learning. I will follow up of the answer in comments below. Recently my friend Vinod Kumar wrote excellent blog post on SQL Server 2012: Using SEQUENCE, you can head over there for learning sequence in details.
Reference: Pinal Dave (https://blog.sqlauthority.com)
6 Comments. Leave new
Repost
The Default MINVALUE of the above sequence would be -9223372036854775808 and its a CYCLIC sequence, after exceeding the MAXVALUE 5, the next value of the SEQUENCE will be -9223372036854775808.
Option START WITH 3, is of use when the SEQUENCE is initiated for the first time.
Thanks,
Litesh
Yes. Correct.
Guess what will be the ouput for the below query
SELECT next value FOR dbo.SequenceID, next value FOR dbo.SequenceID