What Are Azure SQL Database Sequences?
Database sequences in Azure SQL are user-defined schema-bound objects that generate a sequence of numeric values according to a specification. Unlike identity columns, sequences are independent of tables and can be used across multiple tables or columns.
Key Features
- Independent of tables: Sequences are not tied to any specific table.
- Reusable: The same sequence can supply values for multiple tables.
- Flexible: You can define starting value, increment, minimum, maximum, and cycling behavior.
Creating a Sequence
CREATE SEQUENCE dbo.OrderNumberSeq
START WITH 1000
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 9999
CYCLE;
Using a Sequence
INSERT INTO Orders (OrderID, Product, Quantity)
VALUES (NEXT VALUE FOR dbo.OrderNumberSeq, 'Widget', 5);
Benefits Over Identity Columns
- Share across tables: Multiple tables can use the same sequence.
- Gap control: You can retrieve the next value without inserting a row.
- Performance: Sequences can be cached to reduce I/O.
Best Practices
- Use sequences when you need unique numbers across multiple tables or when you need to know the value before insertion.
- Consider caching settings for high-volume scenarios.
- Always test for boundary conditions when cycling.
By mastering sequences, you can design more flexible and scalable database solutions in Azure SQL.