# SQL Server IDENTITY vs SEQUENCE: Which Should a Primary Key Use?

> Give a table's own key `IDENTITY` unless you need what only a sequence does: one number space across several tables, a number before the row exists, or a column you can renumber later without rebuilding the table. A sequence default also lets an import write its own ids, which then collide with the sequence. A bare `CREATE SEQUENCE` with no options starts at the most negative `bigint`, so always state `AS` and `START WITH`.

Source: https://schemity.com/blog/sql-server-identity-vs-sequence/

A SQL Server primary key should use `IDENTITY` when it belongs to one table and only the database fills it, and a `SEQUENCE` when the number has to be shared, known before the insert, or changed later. The difference that decides most cases is not speed or gaps but what you can still do after the table exists: an `IDENTITY` is fixed when the column is created, and SQL Server has no statement that adds one to a column, removes one, or changes its step.

Everything below ran on SQL Server 2022 (RTM-CU26, 16.0.4265.3) in a throwaway container, with these two tables:

```sql
CREATE TABLE orders_i (
  id int IDENTITY(1,1) PRIMARY KEY,
  note nvarchar(50) NOT NULL DEFAULT ''
);

CREATE SEQUENCE dbo.order_id_seq AS int START WITH 1 INCREMENT BY 1;
CREATE TABLE orders_s (
  id int NOT NULL CONSTRAINT df_orders_s_id DEFAULT (NEXT VALUE FOR dbo.order_id_seq) PRIMARY KEY,
  note nvarchar(50) NOT NULL DEFAULT ''
);
```

## SQL Server IDENTITY vs SEQUENCE: what is the difference?

An `IDENTITY` is a property of one column that numbers that table's rows, while a sequence is a separate schema object that hands out numbers to whoever asks, usually through a column default.

That one difference produces every row of this table:

| | `IDENTITY` | Sequence default |
|---|---|---|
| Belongs to | One column of one table | Its own object; any table or query can call it |
| An insert that supplies its own id | Refused (Msg 544) unless `SET IDENTITY_INSERT ON` | Accepted, then collides with the sequence later |
| Per table | One (Msg 2744 on a second) | As many defaults as you like |
| Added to an existing column | No: `ALTER COLUMN ... IDENTITY` is a syntax error | Yes: `ADD CONSTRAINT ... DEFAULT ... FOR` |
| Step changed later | No | `ALTER SEQUENCE ... INCREMENT BY` |
| `TRUNCATE TABLE` | Restarts at the seed | Carries on |
| Number before the insert | No; read it back with `SCOPE_IDENTITY()` or `OUTPUT` | `NEXT VALUE FOR` in any query |
| Jump after a crash (default settings) | +1,000 for `int`, +10,000 for `bigint` | Up to the cache; +49 on 2022 CU26 |

## What happens when an import writes its own ids?

`IDENTITY` refuses the row unless you switch on `IDENTITY_INSERT`, while a sequence default accepts it and then hands out the same number later.

On the identity table, `INSERT INTO orders_i (id, note) VALUES (10, 'x')` fails with `Msg 544: Cannot insert explicit value for identity column in table 'orders_i' when IDENTITY_INSERT is set to OFF`. The way through is `SET IDENTITY_INSERT orders_i ON`, and it is limited to one table per session: switching it on for a second table in the same session returned `Msg 8107: IDENTITY_INSERT is already ON for table ... Cannot perform SET operation for table ...`. A data load across many tables has to switch it off and on table by table.

The sequence default looks friendlier and is the riskier of the two. An import wrote `id = 2` with no complaint. The next insert that used the default got 1, and the one after that drew 2 from the sequence and failed: `Msg 2627: Violation of PRIMARY KEY constraint ... The duplicate key value is (2)`. Nothing ties the sequence to the column, so after any load that brings its own ids, restart the sequence above the highest one with `ALTER SEQUENCE dbo.order_id_seq RESTART WITH <max + 1>`. It is the same trap as PostgreSQL's `serial`, described in [serial vs identity](https://schemity.com/blog/postgres-serial-vs-identity/).

## Can you change an IDENTITY column later?

No: SQL Server cannot add `IDENTITY` to an existing column, remove it, or change its step, so any of those means a new table, usually with a copy of the rows.

Three attempts, three refusals. `ALTER TABLE legacy ALTER COLUMN id int IDENTITY(1,1) NOT NULL` is not even parsed (`Msg 156: Incorrect syntax near the keyword 'IDENTITY'`). Putting a sequence default on the identity column instead fails with `Msg 1754: Defaults cannot be created on columns with an IDENTITY attribute`. And Microsoft's [IDENTITY property page](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property) states it plainly: "Once the identity property is set on a column, it can't be removed."

The sequence side of the same changes is ordinary DDL. A legacy table with ids 1 to 3 and no numbering took a default on the existing key with `CREATE SEQUENCE dbo.legacy_seq AS int START WITH 4` and `ALTER TABLE legacy ADD CONSTRAINT df_legacy_id DEFAULT (NEXT VALUE FOR dbo.legacy_seq) FOR id`, and the next insert got 4. Changing the step is `ALTER SEQUENCE dbo.order_id_seq INCREMENT BY 10`, effective on the next value. If a table's numbering is likely to change, that flexibility is the reason to pick the sequence on day one.

## Do IDENTITY and SEQUENCE both leave gaps?

Yes, both do: neither gives back a number from a rolled-back insert, and at default settings both lose their cached numbers when the server stops unexpectedly.

A rolled-back insert into the identity table left ids 1 and 3, and Microsoft's sequence docs say numbers are "consumed whether the transaction using the sequence number is committed or rolled back". The crash gap is the one that surprises people. After two inserts into each table, `SHUTDOWN WITH NOWAIT` and a restart, the next insert got:

| Key | Before the restart | After |
|---|---|---|
| `int IDENTITY` | 1, 2 | 1002 |
| `bigint IDENTITY` | 1, 2 | 10002 |
| `int` sequence, default cache | 1, 2 | 51 |
| `int` sequence, `NO CACHE` | 1, 2 | 3 |

Microsoft's documented fix for the identity jump is `ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF`, available since SQL Server 2017, at some insert cost; `NO CACHE` does the same for a sequence, as the last row shows. If a number must have no gaps, neither object promises it; that needs a counter row updated in the same transaction as the insert.

One more difference: `TRUNCATE TABLE orders_i` started the identity again at 1, while after `TRUNCATE TABLE orders_s` the sequence carried on at 3. Tests that truncate between runs get repeatable ids from `IDENTITY` for free; a sequence also needs an `ALTER SEQUENCE ... RESTART`.

## What does a bare CREATE SEQUENCE start at?

A `CREATE SEQUENCE` with no options is a `bigint` that starts at -9,223,372,036,854,775,808, so a sequence written without `AS` and `START WITH` hands out negative ids.

Microsoft's [CREATE SEQUENCE page](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql) says the default type is `bigint` and the default start is "the minimum value for an ascending sequence object". Measured: `CREATE SEQUENCE dbo.bare_seq` as a `bigint` key's default gave the first row `id = -9223372036854775808`. The same sequence as an `int` key's default refused the first insert with `Msg 8115: Arithmetic overflow error converting expression to data type int`. Write both clauses every time: `CREATE SEQUENCE dbo.order_id_seq AS int START WITH 1`.

## When should a primary key use a sequence instead of IDENTITY?

Use a sequence when the number is shared across tables, needed before the row exists, or likely to change; for every other key, `IDENTITY` is the simpler choice.

**One number space across tables.** Invoices and credit notes that must never share a document number can both default to one sequence. With `CREATE SEQUENCE dbo.doc_no AS bigint START WITH 1000`, alternate inserts gave invoice 1000, credit note 1001 and invoice 1002. While a default uses it, the sequence cannot be dropped by accident: `DROP SEQUENCE dbo.doc_no` failed with `Msg 3729: Cannot DROP SEQUENCE 'dbo.doc_no' because it is being referenced by object 'DF__invoices__id__...'`.

**A number before the insert.** `DECLARE @id int = NEXT VALUE FOR dbo.order_id_seq` reserves an id the application can put on child rows, a file name or a message before the parent row is written, and `sp_sequence_get_range` reserves a block of them for a batch. With `IDENTITY` the id exists only after the insert.

**Numbering you may change.** A new step or a move to a shared number space is one `ALTER` on a sequence and a table rebuild on an identity. A new starting point is cheap on both: `ALTER SEQUENCE ... RESTART WITH` or `DBCC CHECKIDENT ... RESEED`.

Against that, `IDENTITY` keeps the key and its numbering in one place, and refuses stray ids by default. For a table whose ids only ever come from the database, that is the better trade. The choice is the same one as [UUID vs bigint](https://schemity.com/blog/postgres-uuid-vs-bigint-primary-key/) in one respect: it is cheap on day one and expensive once the table holds data.

## How does Schemity handle IDENTITY and sequence keys on SQL Server?

Schemity draws an `IDENTITY` as an Auto increment tick with its start and step, keeps a sequence default as the column's default, and locks an identity change SQL Server cannot make in place.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. To design the next one, the field editor's [Auto increment tick](https://schemity.com/doc/tables-and-fields/#how-do-i-make-the-database-number-a-key) is written as `IDENTITY(start, step)` on SQL Server, and a numbered column takes no default, which matches Msg 1754 above. On a column that already exists in the database, the tick, Start at and Step are locked, and the tick's tooltip says why: SQL Server fixes a column's auto-increment when the column is created, and changing it means rebuilding the table and copying its rows. A change made any other way, such as an edited diagram file, is refused when the migration is planned, for the same reason.

![Schemity's field editor for orders.id open beside the canvas, where orders.id is an INT marked auto and invoices.id and credit_notes.id default to NEXT VALUE FOR [dbo].[doc_no]: PK is ticked, the Auto increment tick is ticked but greyed out, Start at 1 and Step 1 are greyed out too, and the tooltip over the tick reads SQL Server fixes a column's auto-increment when the column is created. Changing it means rebuilding the table and copying its rows, which Schemity does not do.](https://schemity.com/images/blog/sql-server-identity-vs-sequence/identity-locked.webp)

A key that defaults to a sequence is read from the live database with its `NEXT VALUE FOR` default and written back as it is. Import SQL and the free [Migration Check](https://schemity.com/doc/migration-check-ci/) read the same default in a script, along with SQL Server's own `ALTER TABLE ... ADD DEFAULT ... FOR` form. Schemity does not create the sequence on SQL Server: the `CREATE SEQUENCE`, with its `AS` and `START WITH`, stays in your migration. [Impact analysis](https://schemity.com/doc/impact-analysis/), a Schemity Pro feature, shows the rest of a key change, such as widening an identity from `int` to `bigint`, before it is applied.

![Schemity's canvas reading three tables from SQL Server 16.0.4265.3: orders.id is an INT primary key marked auto for its IDENTITY, with note NVARCHAR(50) defaulting to an empty string; invoices.id and credit_notes.id are BIGINT primary keys whose default reads NEXT VALUE FOR [dbo].[doc_no], each beside total DECIMAL(12,2) defaulting to 0](https://schemity.com/images/blog/sql-server-identity-vs-sequence/canvas-identity-and-sequence.webp)

For the next decision on the same key, read [changing an INT primary key to BIGINT on SQL Server](https://schemity.com/blog/sqlserver-change-int-to-bigint-primary-key/), and for what a foreign key should point at, [natural key vs surrogate key](https://schemity.com/blog/natural-key-vs-surrogate-key-foreign-key/).

## Frequently asked questions

### Should I use IDENTITY or SEQUENCE for a primary key in SQL Server?

Use `IDENTITY` for a key that belongs to one table and is only ever filled by the database. Use a sequence with a `DEFAULT (NEXT VALUE FOR s)` when several tables share one number space, when the application needs the id before it inserts the row, or when you expect to change the numbering later, because `IDENTITY` cannot be added, removed or re-stepped on an existing column.

### Can I convert an IDENTITY column to a SEQUENCE in SQL Server?

Not in place. SQL Server refuses a default on an `IDENTITY` column with Msg 1754, and has no statement that removes the property. The usual route is a new table whose key defaults to the sequence, the rows copied across with their ids, the sequence restarted above the highest id, and the tables swapped by rename.

### Why did my SQL Server identity jump by 1000?

SQL Server caches identity values, and an unexpected shutdown loses the cache. Measured on SQL Server 2022, an `int` identity went from 2 to 1002 and a `bigint` identity from 2 to 10002 after `SHUTDOWN WITH NOWAIT`. Microsoft documents `ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF` as the way to avoid it, at some insert cost; a sequence with `NO CACHE` lost nothing in the same test.
