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