postgres sequence - ghdrako/doc_snipets GitHub Wiki
sequence postgres
CREATE SEQUENCE name [INCREMENT [ BY ]
increment][ MINVALUE minvalue | NO MINVALUE ] [
MAXVALUE maxvalue| NO MAXVALUE ][ START [ WITH ]
start ] [ CACHE cache ] [ [ NO ] CYCLE]
Sequence Functions:
- nextval(regclass) -> bigint
- Increments sequence value set as per increment value set at the time of creating the sequence and return next incremented value in the sequence.
- By default, it increments the value by 1.
- It needs USAGE and UPDATE privileges on the sequence.
- Syntax:
SELECT NEXTVAL(βSCHEMA_NAME.SEQ_NAMEβ)
where SCHEMA_NAME is the schema name and SEQ_NAME is the sequence name. - Eg:
SELECT NEXTVAL(βtest_schema.test_seqβ);
- currval(regclass) -> bigint
- It gives the latest used value for a specific sequence.
- It gives session level value, and in case nextval is not initiated, then it will give an error.
SELECT currval('sale_id_seq');
ERROR: currval of sequence "sale_id_seq" is not yet defined in this session
- It also needs USAGE and UPDATE privileges on the sequence.
- setval (regclass, bigint [, boolean ]) β bigint
- This function can set a custom value for the sequence.
- It needs the UPDATE privilege on the sequence.
- For example:
select setval(βtest_schema.test_seqβ,99)
# Next nextval will return 100
select setval(βtest_schema.test_seqβ,99,true)
# Next nextval will return 100
select setval(βtest_schema.test_seqβ,99,false)
#Next nextval will return 99
- lastval() β bigint
- Determines the last value used in the particular session.
- It gives session level value, and in case nextval is not initiated, then it will give an error.
- This function is identical to currval, except that instead of taking the sequence name as an argument, it refers to whichever sequence nextval was most recently applied to in the current session. (Reference: PostgreSQL Community Sequences).
In PostgreSQL 10 the view pg_sequences was added to provide easy access to information about sequences:
SELECT * FROM pg_sequences WHERE sequencename = 'sale_id_seq';
β[ RECORD 1 ]ββ¬ββββββββββββ
schemaname β public
sequencename β sale_id_seq
sequenceowner β db
data_type β integer
start_value β 1
min_value β 1
max_value β 2147483647
increment_by β 1
cycle β f
cache_size β 1
last_value β 155
Another way to get the current value of a sequence is using the undocumented function pg_sequence_last_value:
db=# SELECT pg_sequence_last_value('sale_id_seq');
pg_sequence_last_value
ββββββββββββββββββββββββ
155
You can also query a sequence, just like you would a table:
db=# SELECT * FROM sale_id_seq;
last_value β log_cnt β is_called
βββββββββββββΌββββββββββΌβββββββββββ
155 β 10 β t