Sequence functions
NEXTVAL, LASTVAL and SETVAL, with the NEXT VALUE FOR and PREVIOUS VALUE FOR forms.
A sequence is a database object that makes numbers one after the other. CREATE SEQUENCE, ALTER SEQUENCE, DROP SEQUENCE and SHOW CREATE SEQUENCE are on the page for CREATE SEQUENCE.
Sequences are a MariaDB feature. Raft DB provides them in both dialects. The state is shared by all sessions of the front-end; LASTVAL is the session's.
The output is identical to MariaDB 11.4.13.
Summary of functions#
| Function | What it does | Dialect |
|---|---|---|
LASTVAL | Returns the value NEXTVAL last gave this session for the sequence, NULL if it has not given one. | MySQL and MariaDB |
NEXTVAL | Moves the sequence on and returns the new value. | MySQL and MariaDB |
SETVAL | Sets the next value of the sequence. | MySQL and MariaDB |
LASTVAL#
LASTVAL(sequence)
PREVIOUS VALUE FOR sequenceReturns the value NEXTVAL last gave this session for the sequence, NULL if it has not given one. The value is the session's own.
Example:
CREATE SEQUENCE s1;
SELECT NEXTVAL(s1), NEXTVAL(s1), NEXT VALUE FOR s1;
SELECT LASTVAL(s1), PREVIOUS VALUE FOR s1;Result: 1, 2, 3; then 3, 3
NEXTVAL#
NEXTVAL(sequence)
NEXT VALUE FOR sequenceMoves the sequence on and returns the new value. The sequence is named as a table is (s1 or db.s1). Error 4084 when a sequence without CYCLE has reached its limit; error 4091 for a sequence that does not exist. Values are reserved in blocks of the sequence's CACHE, so a restart of the server skips the values that were reserved and not used. A column can take its default from it: DEFAULT NEXTVAL(s1) or DEFAULT (NEXT VALUE FOR s1).
Example:
CREATE SEQUENCE s1;
SELECT NEXTVAL(s1);Result: 1
SETVAL#
SETVAL(sequence, value [, is_used [, round]])Sets the next value of the sequence. With is_used true (the default) value counts as used and the next NEXTVAL gives value plus the increment; with 0 the next NEXTVAL gives value. A value that is not ahead of the sequence's position (in the direction of its increment) changes nothing and gives NULL. The round argument is read and ignored. Returns value.
Example:
CREATE SEQUENCE s1;
SELECT NEXTVAL(s1), NEXTVAL(s1), NEXTVAL(s1);
SELECT SETVAL(s1, 50), NEXTVAL(s1);
SELECT SETVAL(s1, 60, 0), NEXTVAL(s1);
SELECT SETVAL(s1, 10);Result: 50, 51; then 60, 60; then NULL