CREATE_SEQUENCE(7pg17)
β¨ CREATE SEQUENCE β¨
okay so this is the CREATE SEQUENCE(7) page from the PostgreSQL 17.11 docs, and honestly? it's kind of a bop. buckle up bestie, we're making number generators π
π NAME π
CREATE_SEQUENCE β define a new sequence generator. that's it, that's the whole vibe. it makes numbers go brrr. β¨
π¦ SYNOPSIS π¦
CREATE [ { TEMPORARY | TEMP } | UNLOGGED ] SEQUENCE [ IF NOT EXISTS ] name
[ AS data_type ]
[ INCREMENT [ BY ] increment ]
[ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
[ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]
[ OWNED BY { table_name.column_name | NONE } ]
π DESCRIPTION π
so CREATE SEQUENCE literally creates a brand-new sequence number generator. the way it works? it makes and initializes a whole new special single-row table with the name name, and the generator is owned by whoever ran the command (main character energy, ngl π).
if you give it a schema name, the sequence gets created in that schema. if you don't, it goes in the current schema, easy. temporary sequences live in a special schema, so bestie β you literally cannot give a schema name when you're creating a temporary sequence, that's just not a thing. also, the sequence name has to be distinct from the name of any other relation in that same schema β and by "relation" i mean table, sequence, index, view, materialized view, or foreign table. all of them. π
once it exists, you use the functions nextval, currval, and setval to actually work on the sequence. those are documented in Section 9.17, iykyk.
and like β you can't update a sequence directly, but you can run a query like this:
SELECT * FROM name;
to peek at the parameters and current state of a sequence. specifically, the last_value field shows the last value allocated by any session. (obviously that value might already be stale by the time it's printed if other sessions are actively hitting nextval, so don't come for me π)
πΈ PARAMETERS πΈ
TEMPORARYorTEMPβ if you say this, the sequence object exists only for this session and gets automatically dropped when the session exits. existing permanent sequences with the same name are not visible in this session while the temporary one exists β unless you reference them with schema-qualified names. sneak peek privileges only π«ΆUNLOGGEDβ if you say this, the sequence is created as an unlogged sequence. changes to unlogged sequences are not written to the write-ahead log. they are not crash-safe: an unlogged sequence is automatically reset to its initial state after a crash or unclean shutdown. unlogged sequences are also not replicated to standby servers. π«
but like, unlike unlogged tables, unlogged sequences do not offer a significant performance advantage. this option is mainly intended for sequences associated with unlogged tables via identity columns or serial columns. in those cases it usually wouldn't make sense to have the sequence WAL-logged and replicated but not its associated table. make it make sense, right?
IF NOT EXISTSβ do not throw an error if a relation with the same name already exists. a notice gets issued instead. but heads up: there is no guarantee that the existing relation is anything like the sequence that would have been created β it might not even be a sequence π like it could be literally anything. no cap.nameβ the name (optionally schema-qualified) of the sequence to be created. pick something cute.data_typeβ the optional clauseAS data_typespecifies the data type of the sequence. valid types aresmallint,integer, andbigint.bigintis the default. the data type determines the default minimum and maximum values of the sequence. β¨incrementβ the optional clauseINCREMENT BY incrementspecifies which value is added to the current sequence value to create a new value. a positive value makes an ascending sequence, a negative one makes a descending sequence. default is1. simple as.minvalue/NO MINVALUEβ the optional clauseMINVALUE minvaluedetermines the minimum value a sequence can generate. if this clause isn't supplied, orNO MINVALUEis specified, then defaults are used. the default for an ascending sequence is1. the default for a descending sequence is the minimum value of the data type.maxvalue/NO MAXVALUEβ the optional clauseMAXVALUE maxvaluedetermines the maximum value for the sequence. if this clause isn't supplied, orNO MAXVALUEis specified, then default values are used. the default for an ascending sequence is the maximum value of the data type. the default for a descending sequence is-1.startβ the optional clauseSTART WITH startlets the sequence begin anywhere it wants, honestly. the default starting value isminvaluefor ascending sequences andmaxvaluefor descending ones.cacheβ the optional clauseCACHE cachespecifies how many sequence numbers are preallocated and stored in memory for faster access. the minimum value is1(only one value can be generated at a time, i.e., no cache), and that's also the default. lowkey the safe choice.CYCLE/NO CYCLEβ theCYCLEoption lets the sequence wrap around when themaxvalueorminvaluehas been reached by an ascending or descending sequence respectively. if the limit is reached, the next number generated will be theminvalueormaxvalue, respectively. round and round we go π
if NO CYCLE is specified, any calls to nextval after the sequence has reached its maximum value will return an error. if neither CYCLE nor NO CYCLE are specified, NO CYCLE is the default.
OWNED BY table_name.column_name/OWNED BY NONEβ theOWNED BYoption causes the sequence to be associated with a specific table column, such that if that column (or its whole table) is dropped, the sequence gets automatically dropped too. they go down together, ride or die π the specified table must have the same owner and be in the same schema as the sequence.OWNED BY NONE, the default, specifies that there is no such association.
π NOTES π
use DROP SEQUENCE to remove a sequence. bye bestie π
sequences are based on bigint arithmetic, so the range cannot exceed the range of an eight-byte integer (-9223372036854775808 to 9223372036854775807). that's the whole range, no exceptions.
because nextval and setval calls are never rolled back, sequence objects cannot be used if you need "gapless" assignment of sequence numbers. it is possible to build gapless assignment by using exclusive locking of a table containing a counter β but that solution is much more expensive than sequence objects, especially if many transactions need sequence numbers concurrently. so like, pick your fighter π
unexpected results might be obtained if a cache setting greater than one is used for a sequence object that will be used concurrently by multiple sessions. each session will allocate and cache successive sequence values during one access to the sequence object and increase the sequence object's last_value accordingly. then, the next cache-1 uses of nextval within that session simply return the preallocated values without touching the sequence object. so, any numbers allocated but not used within a session will be lost when that session ends, resulting in "holes" in the sequence. holes! the audacity π
furthermore, although multiple sessions are guaranteed to allocate distinct sequence values, the values might be generated out of sequence when all the sessions are considered. for example, with a cache setting of 10, session A might reserve values 1..10 and return nextval=1, then session B might reserve values 11..20 and return nextval=11 before session A has generated nextval=2. so, with a cache setting of one it is safe to assume that nextval values are generated sequentially; with a cache setting greater than one you should only assume that the nextval values are all distinct, not that they are generated purely sequentially. also, last_value will reflect the latest value reserved by any session, whether or not it has yet been returned by nextval.
another consideration: a setval executed on such a sequence will not be noticed by other sessions until they have used up any preallocated values they have cached. so like, patience bestie π§
π EXAMPLES π
create an ascending sequence called serial, starting at 101:
CREATE SEQUENCE serial START 101;
select the next number from this sequence:
SELECT nextval('serial');
nextval
---------
101
select the next number from this sequence:
SELECT nextval('serial');
nextval
---------
102
it's giving consistent. she ate π₯
use this sequence in an INSERT command:
INSERT INTO distributors VALUES (nextval('serial'), 'nothing');
update the sequence value after a COPY FROM:
BEGIN;
COPY distributors FROM 'input_file';
SELECT setval('serial', max(id)) FROM distributors;
END;
β COMPATIBILITY β
CREATE SEQUENCE conforms to the SQL standard, with the following exceptions:
- obtaining the next value is done using the
nextval()function instead of the standard'sNEXT VALUE FORexpression. - the
OWNED BYclause is a PostgreSQL extension.
π SEE ALSO π
ALTER SEQUENCE (ALTER_SEQUENCE(7)), DROP SEQUENCE (DROP_SEQUENCE(7))
okay that's the whole page, you're basically a sequence girlie now ππ huge shoutout to the PostgreSQL 17.11 docs, dated 2026 β this has been CREATE SEQUENCE(7), signing off, slay β¨π¦π
π¦ where this page comes from
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms