// tables reference

SQL CREATE SEQUENCE

Makes a number generator that lives outside any table and hands out increasing values on demand. Three engines ship one; MySQL and SQLite build the counter into the table instead.

Категория
Таблицы
In this category
15 of 16

Синтаксис

CREATE SEQUENCE [IF NOT EXISTS] name [AS type] [START WITH n] [INCREMENT BY n]  -- PostgreSQL: plus MINVALUE, MAXVALUE, CYCLE, CACHE, OWNED BY
CREATE SEQUENCE name START WITH 1 INCREMENT BY 1  -- SQL Server, Oracle: pulled with NEXT VALUE FOR name or name.NEXTVAL
-- MySQL: no sequences; AUTO_INCREMENT on a key column is the counter
-- SQLite: no sequences; an INTEGER PRIMARY KEY column counts by itself

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да since 2012; not tied to any column, values come from NEXT VALUE FOR name
PostgreSQL Да OWNED BY table.column ties the sequence's life to a column, which is what serial sets up
MySQL No equivalent no CREATE SEQUENCE; AUTO_INCREMENT columns are the counter (MariaDB, a fork, has its own)
SQLite No equivalent no sequences at all; the rowid behind INTEGER PRIMARY KEY is the counter
Oracle Да values via name.NEXTVAL, current via name.CURRVAL; from 12.1 a column DEFAULT can call it

Примеры

PostgreSQL

CREATE SEQUENCE invoice_number START WITH 1000 INCREMENT BY 1;
SELECT nextval('invoice_number');

PostgreSQL

-- serial does this wiring for you: the sequence dies with the column
CREATE SEQUENCE order_id_seq OWNED BY orders.id;
ALTER TABLE orders ALTER COLUMN id SET DEFAULT nextval('order_id_seq');

SQL Server

CREATE SEQUENCE dbo.invoice_number AS BIGINT START WITH 1000 INCREMENT BY 1;
-- pull values:
SELECT NEXT VALUE FOR dbo.invoice_number;

Oracle

CREATE SEQUENCE invoice_number START WITH 1000 INCREMENT BY 1 NOCACHE;
SELECT invoice_number.NEXTVAL FROM dual;

MySQL

-- the MySQL way: the counter lives in the table
CREATE TABLE invoices (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  total_cents INT NOT NULL
);

SQLite

-- the SQLite way: rowid doubles as the counter
CREATE TABLE invoices (
  id INTEGER PRIMARY KEY,
  total_cents INTEGER NOT NULL
);

Полезно знать

  • Sequences are transaction-proof on purpose: a rolled-back insert still burns the number, and no two sessions get the same one unless the sequence was declared CYCLE and has wrapped around. Gaps in a sequence-fed id are normal operation, not a sign of trouble.
  • SQL Server's sequence belongs to no column: the link is a DEFAULT expression calling NEXT VALUE FOR, and that dependency blocks dropping the sequence until you remove or alter the default. There is no OWNED BY clause.
  • Scripts ported between MySQL and MariaDB break quietly: MariaDB 10.3+ has CREATE SEQUENCE, real MySQL does not, so a script that runs green on one fails at parse on the other.
  • Oracle dispenses values in cached batches, 20 by default; an instance restart discards the unused tail of the batch and widens the gap. NOCACHE narrows the gaps at the cost of every session serializing on one counter.

Questions about CREATE SEQUENCE

Will a sequence give me gap-free invoice numbers?

No. nextval(), NEXT VALUE FOR and .NEXTVAL all burn numbers on rollback and restarts, by design. If the business needs consecutive numbers, generate them inside the transaction that writes the row, or use a dedicated counter table with row locking.

Sequence or identity column?

For one table's surrogate key, the built-in forms win: IDENTITY on SQL Server, GENERATED AS IDENTITY on PostgreSQL and Oracle, AUTO_INCREMENT on MySQL, INTEGER PRIMARY KEY on SQLite. A standalone sequence earns its keep when several tables share one numbering space, or when you need to reserve ranges at once (SQL Server's sp_sequence_get_range).

How does MySQL fill a sequence's role?

AUTO_INCREMENT: one column per table, and it must be a key (the primary key in practice). The counter lives in the table's metadata; TRUNCATE TABLE resets it, DELETE does not.

Browse every statement in the SQL DDL reference, or see what the SQLly desktop app does for your database.

// dialect-aware editing

DDL that matches the engine you're connected to

SQLly checks your statements against the dialect of the open connection, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle, so an ALTER TABLE that works on one engine gets flagged before it runs on another.