Tables and integrity
IDENTITY and sequences
Generate surrogate values while recognizing that gaps are possible.
Lesson 56 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Generate surrogate values while recognizing that gaps are possible. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
CREATE TABLE #Tickets (TicketID int IDENTITY(1,1) PRIMARY KEY, Label nvarchar(20) NOT NULL);
INSERT INTO #Tickets (Label) VALUES (N'First'), (N'Second');
SELECT TicketID, Label FROM #Tickets ORDER BY TicketID;
DROP TABLE #Tickets;Read it step by step
- IDENTITY(1,1) generates values starting at 1 with increment 1 for this table.
- The INSERT omits TicketID and SQL Server supplies each value.
- A SEQUENCE is a separate object that can supply numbers to multiple uses; neither mechanism guarantees gap-free business numbering.
Check the result
| TicketID | Label |
|---|---|
| 1 | First |
| 2 | Second |
The displayed 1 and 2 are from this fresh temp table, not a promise for all future inserts.
Practice
Create a disposable SEQUENCE starting at 10 and increasing by 2, show values for Products 1 and 2, then roll back.
Check your answer and expected result
Reveal answer
BEGIN TRANSACTION;
CREATE SEQUENCE dbo.DDI_LessonSequence AS int START WITH 10 INCREMENT BY 2;
SELECT ProductID,
NEXT VALUE FOR dbo.DDI_LessonSequence OVER (ORDER BY ProductID) AS TicketID
FROM dbo.Products WHERE ProductID IN (1, 2)
ORDER BY ProductID;
ROLLBACK TRANSACTION;| ProductID | TicketID |
|---|---|
| 1 | 10 |
| 2 | 12 |
The sequence supplies 10 and 12 in ProductID order. Rollback removes the practice sequence object; sequence values are not promised gap-free in real use.
Your progress
Reveal the check answer or reach the end to complete this lesson.