Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • SQL Server - Get Started
  • Install SQL Server
  • SQL Server Management Studio
  • SQL Server - Windows Authentication
  • SQL Server - Authentication
  • SQL Server - Create New User
  • SQL Server - GRANT/REVOKE Permissions to User
  • SQL Server - Data Types
  • SQL Server - Naming Conventions
  • SQL Server - CREATE Database
  • SQL Server - CREATE Table
  • Add Columns
  • Identity Column
  • Rename Column, Table
  • Drop Columns
  • SQL Server - Schema
  • SQL Server - Tables Relations
  • SQL Server - Primary Keys
  • Modify/Delete Primary Keys
  • SQL Server - Foreign Keys
  • Modify/Delete Foreign Keys
  • SQL Server - Check Constraints
  • SQL Server - Unique Constraints
  • SQL Server - Views
  • Modify/Delete Views
  • SQL Server - Functions
  • SQL Server - Stored Procedures
  • Stored Procedure Parameters
  • SQL Server - Indexes
  • Non-clustered Indexes
  • Modify/Delete Indexes
  • SQL Server - Triggers
  • DDL Triggers
  • LOGON Triggers
  • Enable/Disable Triggers
  • Modify/Delete Triggers
  • SQL Server - Sequence
  • SQL Server - Synonyms
  • SQL Server - IF ELSE Statement
  • SQL Server - Loops
  • SQL Server - Insert Data
  • SQL Server - Update Data
  • SQL Server - Delete Data
  • SQL Server - Select Query
  • WHERE Clause
  • GROUP BY Clause
  • HAVING Clause
  • ORDER BY Clause
  • SQL Server - Inner Join
  • Left Join
  • Right Join
  • Full Join
  • Self Join
  • Dynamic SQL
  • Built-in Functions
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Sequence in SQL Server

In SQL Server, the sequence is a schema-bound object that generates a sequence of numbers either in ascending or descending order in a defined interval. It can be configured to restart when the numbers get exhausted.

  • A Sequence is not associated with any table.
  • You can refer a sequence to generate values with specific increment and interval on each execution by using NEXT VALUE FOR. You don't need to insert a row in a table (like identity column) to generate the sequence.

Use the CREATE SEQUENCE statement to create a sequence.

Syntax:
CREATE SEQUENCE [schema_name.] sequence_name  
    [ AS [ integer_type ] ]  
    [ START WITH start_value ]  
    [ INCREMENT BY increment_value ]  
    [ { MINVALUE [ minvalue } | { NO MINVALUE } ]  
    [ { MAXVALUE [ maxvalue ] } | { NO MAXVALUE } ]  
    [ CYCLE | { NO CYCLE } ]  
    [ { CACHE [ size ] } | { NO CACHE } ];

In the above syntax:

  • schema_name: SCHEMA associated with the Sequence.
  • sequence_name: A unique name given to the sequence in a database.
  • integer_type: A sequence is defined with any of the integer types as tinyint, smallint, int, bigint, numeric, decimal, or a user - defined data type.
  • start_value: The first value in the sequence.
  • increment_value: This is the interval between two consecutive sequence values. If the increment value is negative, then the sequence is a decreasing sequence else it is ascending. The default increment value is 1. The Increment cannot be 0.
  • minvalue | NO MINVALUE: This specifies the lower bound for a sequence. If not specified, it defaults to the minimum value of the data type of the sequence.
  • maxvalue | NO MAXVALUE : specifies the upper bound for the sequence. It defaults to the maximum value of the data type of the sequence.
  • CYCLE | NO CYCLE: Specifies whether the sequence object should restart from the minimum value (maximum value for descending sequence) or raise an exception when the minimum (or maximum) value is reached. NO CYCLE is the default value.
  • Note: Cycling will restart the sequence from the minimum or maximum value and not from the start value.
  • CACHE [ size ] | NO CACHE: Improves performance for applications using sequence objects by minimizing the number of disk IOs that are required to generate sequence numbers.

Note: SQL Serve pre-allocates the number of sequence numbers specified by the CACHE.

Let's create a simple Sequence that starts from 5 with an increment of 2.

Example: Create Sequence
CREATE SEQUENCE SequenceCounter
    AS INT
    START WITH 5
    INCREMENT BY 2;
Sequence in SQL Server

The new sequence is created under the Programmability -> Sequence folder, as shown below.

Sequence in SQL Server

You can now execute the above sequence SequenceCounter using NEXT VALUE FOR <sequence-name>. The SequenceCounter will return 5 when you execute it for the first time.

Example: Use Sequence
SELECT NEXT VALUE FOR SequenceCounter AS Counter;
Sequence in SQL Server

Now, execute the same sequence again. The counter is incremented by 2 as specified in the CREATE SEQUENCE statement.

Example: USe Sequence
SELECT NEXT VALUE FOR SequenceCounter AS Counter;
Sequence in SQL Server

Every time you execute the SequenceCounter, the counter is incremented by 2.

Create a Sequence with Min, Max, Cycle

In the following example, a sequence is created with data type as Decimal(3,0). It starts with 10 and every time the sequence is executed, it is incremented by 5. The maximum value is 500. It stops after reaching 500 and since CYCLE is specified, the counter restarts from 10 again.

Example: Decimal Sequence
CREATE SEQUENCE dbo.MyDecSequence  
    AS decimal (3,0)   
    START WITH 10  
    INCREMENT BY 5  
    MINVALUE 10  
    MAXVALUE 500  
    CYCLE  
    CACHE 5 ;

Use SEQUENCE with a Table

You can use a sequence with the table while inserting or updating records. For example, consider the following table.

Example: Create a Table
CREATE TABLE Training(
    TrainingId int PRIMARY KEY,
    TrainingName nvarchar(50) NOT NULL,
    TrainingDate date NOT NULL)
);

Now, use the SequenceCounter sequence in the INSERT statement to insert TrainingId values, as shown below.

Example: Use Sequence in Insert Statement
INSERT INTO Training(TrainingId, TrainingName, TrainingDate)
VALUES(NEXT VALUE FOR SequenceCounter, 'SEO' , '11/23/2022');

INSERT INTO Training(TrainingId, TrainingName, TrainingDate)
VALUES(NEXT VALUE FOR SequenceCounter, 'SQL Server', '11/24/2022');

Now, let's check the inserted values using the select query.

Example:
SELECT * FROM dbo.Training
Sequence in SQL Server

You can see that the TrainingId column of the Training table is populated with numbers generated by using the sequence.

Though, the IDENTITY column also generates sequence numbers, there are a few instances where Sequence is used instead of identity column:

  • You want to share the sequence number across multiple tables.
  • You need to generate a sequence number in the application before inserting it into a table.
  • You need the counter to restart after a certain number is reached.
  • To get several sequence numbers at the same time. You can use the stored procedure sp_sequence_get_range to retrieve several numbers at the same time.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.