DEFINE SEQUENCE statementAvailable since: v3.0.0-beta
A sequence is used to generate reliable, monotonically increasing numeric sequences in both single-node and clustered SurrealDB deployments (multiple compute nodes backed by TiKV). It uses a batch-allocation strategy to minimise coordination while guaranteeing global uniqueness.
The key features of a sequence are as follows:
The sequence implementation avoids contention by having each node reserve a range of sequence values, allowing it to serve multiple requests locally without requiring distributed coordination for every request. When a node exhausts its allocated range, it acquires a new batch from the distributed store.
SurrealQL SyntaxDEFINE SEQUENCE [ OVERWRITE | IF NOT EXISTS ] @name [ BATCH @batch ] [ START @start ] [ TIMEOUT @duration ]
A sequence can be created with nothing more than a name.
DEFINE SEQUENCE mySeq;
The BATCH, START, and ‘TIMEOUT’ clauses can be included to configure the sequence.
DEFINE SEQUENCE mySeq2 BATCH 1000 START 100 TIMEOUT 5s; sequence::nextval('mySeq2'); -- Output: 100 DEFINE SEQUENCE mySeq3 BATCH 1000 START 100 TIMEOUT 0ns; sequence::nextval('mySeq3'); -- Possible output: 'The query was not executed because it exceeded the timeout'
Sequences are never rolled back, even in a failed transaction. This differs from an approach like a single record with a manually incrementing value.
DEFINE SEQUENCE seq; CREATE my:counter SET val = 0; sequence::nextval("seq"); -- 0 my:counter.val; -- 0 BEGIN TRANSACTION; sequence::nextval("seq"); -- 0 UPDATE my:counter SET val += 1; -- my:counter.val = 1 CANCEL TRANSACTION; -- my:counter.val now rolled back to 0 sequence::nextval("seq"); -- 2 UPDATE my:counter SET val += 1; -- 1