w3resource logo


PostgreSQL

PostgreSQL: Sequence

Secondary Nav

Introduction

The sequence is a feature by some database products from which multiple users can generate unique integers. The sequence generator generates sequential numbers, which can help to generate unique primary keys automatically and to coordinate keys across multiple rows or tables.

Create Sequence

In PostgreSQL, CREATE SEQUENCE statement creates a new sequence number generator. This involves creating and initializing a new special single-row table with the name. The generator will be owned by the user who issues the command.

The sequence name must be distinct from the name of any other sequence, table, index, view, or foreign table in the same schema. If a schema name is given then the sequence is created in the specified schema, otherwise, it is created in the current schema. Temporary sequences exist in a special schema, so a schema name cannot be given when creating a temporary sequence.

After a sequence is created, you can use nextval, currval, and setval functions to operate on the sequence.

Sequences are based on bigint arithmetic, so the range cannot exceed the range of an eight-byte integer (-9223372036854775808 to 9223372036854775807).

Syntax

CREATE [ TEMPORARY | TEMP ] SEQUENCE name [ 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 } ]
Option Description
TEMPORARY or TEMP If specified, the sequence object is created only for this session and is automatically dropped on session exit.
name The name of the sequence to be created.
increment The optional clause INCREMENT BY increment specifies which value is added to the current sequence value to create a new value. A positive value will make an ascending sequence, a negative one a descending sequence. The default value is 1.
minvalue
NO MINVALUE
The optional clause MINVALUE minvalue determines the minimum value a sequence can generate. If NO MINVALUE is specified, then defaults will be used. The defaults are 1 and -263-1 for ascending and descending sequences, respectively.
maxvalue
NO MAXVALUE
The optional clause MAXVALUE maxvalue determines the maximum value for the sequence. If NO MAXVALUE is specified, then default values will be used. The defaults are 263-1 and -1 for ascending and descending sequences, respectively.
start The optional clause START WITH start allows the sequence to begin anywhere. The default starting value is minvalue for ascending sequences and maxvalue for descending ones.
cache The optional clause CACHE cache specifies how many sequence numbers are to be preallocated and stored in memory for faster access. The minimum value is 1which is also the default.
CYCLE
NO CYCLE
The CYCLE option allows the sequence to wrap around when the maxvalue or minvalue has been reached by an ascending or descending sequence respectively. If the limit is reached, the next number generated will be the minvalue or maxvalue, respectively.
For NO CYCLE, any calls to nextval after the sequence has reached its maximum value will return an error.
NO CYCLE is the default.
OWNED BY table_name.column_name
OWNED BY NONE
The OWNED BY option causes the sequence to be associated with a specific table column, such that if that column (or its whole table) is dropped, the sequence will be automatically dropped as well. 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.

Drop a Sequence :

Use DROP SEQUENCE to remove a sequence.

Examples :

Create an ascending sequence called idno, starting at 50:

postgres=# CREATE SEQUENCE idno START 50;
CREATE SEQUENCE
postgres=#

Select the next number from this sequence :

postgres=# SELECT nextval('idno');
 nextval
---------
      50
(1 row)

Select the next number from this sequence :

postgres=# SELECT nextval('idno');
 nextval
---------
      51
(1 row)

Note : Here nextval() function is used to get the next value instead of the standard's NEXT VALUE FOR expression.

Let use this sequence in an INSERT command :

Now use the above sequence in an INSERT command :

Sample table 'test' :

postgres=# SELECT * FROM test;
 id | sname | roll_num
----+-------+----------
(0 rows)

Now insert some records :

postgres=# INSERT INTO test VALUES (nextval('idno'), 'Surya', 1);
INSERT 0 1
postgres=# SELECT * FROM test;
 id |                       sname                        | roll_num
----+----------------------------------------------------+----------
 52 | Surya                                              |        1
(1 row)


postgres=# INSERT INTO test VALUES (nextval('idno'), 'Dany', 2);
INSERT 0 1
postgres=# SELECT * FROM test;
 id |                       sname                        | roll_num
----+----------------------------------------------------+----------
 52 | Surya                                              |        1
 53 | Dany                                               |        2
(2 rows)

Inside the sequence :

postgres=# select * from idno;
 sequence_name | last_value | start_value | increment_by |      max_value      | min_value | cache_value | log_cnt | is_cycled | is_called
---------------+------------+-------------+--------------+---------------------+-----------+-------------+---------+-----------+-----------
 idno          |         53 |          50 |            1 | 9223372036854775807 |         1 |           1 |      31 | f         | t
(1 row)


Join our Question Answer community to learn and share your programming knowledge.