SQL sequences: NEXTVAL and NEXT VALUE FOR
A sequence hands out increasing numbers independent of any table, so several tables or an application can share one counter.
- カテゴリ
- System & session
- Returns
bigint (NUMBER on Oracle)- In this category
- 11 of 13
構文
nextval('seq')
seq.NEXTVAL
NEXT VALUE FOR seq
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | Different name or syntax | NEXT VALUE FOR seq; sequences exist from 2012 |
| PostgreSQL | はい | nextval('seq'), currval('seq'), setval |
| MySQL | Not built in | no sequences; AUTO_INCREMENT columns |
| SQLite | Not built in | no sequences; INTEGER PRIMARY KEY or AUTOINCREMENT |
| Oracle | Different name or syntax | seq.NEXTVAL and seq.CURRVAL |
例
PostgreSQL
CREATE SEQUENCE invoice_no START 1000;
SELECT nextval('invoice_no') AS a, nextval('invoice_no') AS b; -- 1000, 1001
SELECT currval('invoice_no'); -- 1001
SQL Server
CREATE SEQUENCE invoice_no START WITH 1000; SELECT NEXT VALUE FOR invoice_no AS a; -- 1000 SELECT NEXT VALUE FOR invoice_no AS b; -- 1001
Oracle
CREATE SEQUENCE invoice_no START WITH 1000; SELECT invoice_no.NEXTVAL AS a, invoice_no.NEXTVAL AS b FROM dual; -- 1000, 1000 DROP SEQUENCE invoice_no;
知っておくと便利なこと
- Sequence values are not rolled back. A failed or rolled-back insert leaves a gap, so never rely on sequences being gapless.
- currval('seq') in PostgreSQL and seq.CURRVAL in Oracle fail until nextval has been called for that sequence in the same session.
- Oracle increments a sequence once per row: two references to seq.NEXTVAL in the same row return the same number.
Questions about NEXTVAL / NEXT VALUE FOR
How do I emulate a sequence in MySQL?
Use a one-row counter table: UPDATE counter SET id = LAST_INSERT_ID(id + 1); then SELECT LAST_INSERT_ID(). The value is per connection, so concurrent sessions each get their own number.
Sequence or identity column?
An identity column (IDENTITY, GENERATED AS IDENTITY, AUTO_INCREMENT) is tied to one table and is simpler. A sequence suits numbers shared across tables or needed before the insert.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.