PostgreSQL Identity & Sequences
Most tables need a unique number for each row. PostgreSQL generates these numbers with sequences: small database objects that hand out increasing values, safely even when many sessions insert at the same time. Identity columns are the modern, standard way to attach a sequence to a column.
Identity columns
CREATE TABLE tickets (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subject text NOT NULL
);
INSERT INTO tickets (subject) VALUES ('Missing page'), ('Late delivery'), ('Wrong book');
SELECT * FROM tickets;CREATE TABLE
INSERT 0 3
id | subject
----+---------------
1 | Missing page
2 | Late delivery
3 | Wrong book
(3 rows)
There are two flavours:
| Definition | Inserting your own value |
|---|---|
GENERATED ALWAYS AS IDENTITY |
refused, unless you write OVERRIDING SYSTEM VALUE |
GENERATED BY DEFAULT AS IDENTITY |
allowed; the sequence is used only when you leave the column out |
CREATE TABLE tickets (id integer GENERATED ALWAYS AS IDENTITY, subject text);
INSERT INTO tickets (id, subject) VALUES (100, 'Manual id');
INSERT INTO tickets (id, subject) OVERRIDING SYSTEM VALUE VALUES (100, 'Manual id');
SELECT * FROM tickets;CREATE TABLE
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
INSERT 0 1
id | subject
-----+-----------
100 | Manual id
(1 row)
The sample tables use BY DEFAULT, which is convenient for loading data with known ids.
Identity options
You can choose the start value and step:
CREATE TABLE invoices (
no integer GENERATED ALWAYS AS IDENTITY (START WITH 1000 INCREMENT BY 10),
amount numeric(8,2)
);
INSERT INTO invoices (amount) VALUES (19.99), (45.00), (7.50);
SELECT * FROM invoices;CREATE TABLE
INSERT 0 3
no | amount
------+--------
1000 | 19.99
1010 | 45.00
1020 | 7.50
(3 rows)
Sequences on their own
Behind every identity column is a sequence. You can also create sequences directly and use them with three functions:
| Function | Does |
|---|---|
nextval('seq') |
advances the sequence and returns the new value |
currval('seq') |
the value most recently returned by nextval in this session |
setval('seq', n) |
sets the current value; the next nextval returns n + 1 |
CREATE SEQUENCE gift_card_no START 501;
SELECT nextval('gift_card_no') AS first, nextval('gift_card_no') AS second;
SELECT currval('gift_card_no') AS current;
SELECT setval('gift_card_no', 900);
SELECT nextval('gift_card_no') AS after_setval;CREATE SEQUENCE
first | second
-------+--------
501 | 502
(1 row)
current
---------
502
(1 row)
setval
--------
900
(1 row)
after_setval
--------------
901
(1 row)
Gaps are normal
Sequences never go backwards. A value taken by an insert that fails (or a transaction that is rolled back) is not reused, so ids can have gaps:
CREATE TABLE members (id integer GENERATED ALWAYS AS IDENTITY, email text UNIQUE);
INSERT INTO members (email) VALUES ('a@example.com');
INSERT INTO members (email) VALUES ('a@example.com'); -- fails, but uses id 2
INSERT INTO members (email) VALUES ('b@example.com');
SELECT * FROM members;CREATE TABLE
INSERT 0 1
ERROR: duplicate key value violates unique constraint "members_email_key"
DETAIL: Key (email)=(a@example.com) already exists.
INSERT 0 1
id | email
----+---------------
1 | a@example.com
3 | b@example.com
(2 rows)
Note: Never use ids to count rows or to assume "no gaps". If you need gapless invoice numbers for legal reasons, generate them in a separate, carefully locked table.
Finding and fixing a sequence
pg_get_serial_sequence tells you which sequence belongs to a column. After loading rows with explicit ids into a BY DEFAULT column, the sequence may lag behind; setval with the current maximum fixes that:
SELECT pg_get_serial_sequence('books', 'id') AS seq;
INSERT INTO categories (id, name) VALUES (50, 'Travel');
SELECT setval(pg_get_serial_sequence('categories', 'id'), (SELECT max(id) FROM categories));
INSERT INTO categories (name) VALUES ('Art') RETURNING id, name; seq
---------------------
public.books_id_seq
(1 row)
INSERT 0 1
setval
--------
50
(1 row)
id | name
----+------
51 | Art
(1 row)
INSERT 0 1
SERIAL: the older way
Older code uses the pseudo-type serial (bigserial for bigint). It also creates a sequence and a default, but it is not part of the SQL standard and its permissions are clumsier. Prefer identity columns in new tables:
-- old style
CREATE TABLE notes (id serial PRIMARY KEY, body text);
-- new style
CREATE TABLE notes (id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text);Test yourself
What does GENERATED ALWAYS AS IDENTITY do when you insert an explicit id?
- Uses your id
- Rejects it unless you add OVERRIDING SYSTEM VALUE
- Ignores it silently
- Adds it to the sequence
An insert with an identity column fails. What happens to the number it took?
- It is reused by the next insert
- It is lost, leaving a gap
- The sequence goes back by one
- The table is locked
After setval('s', 900), what does nextval('s') return?
- 900
- 901
- 1
- It depends on INCREMENT