Sub topic 2
Sequences: the mechanism underneath
Assume you know basic CREATE TABLE, INSERT, and SELECT statements, primary keys, integer types, and the basic idea of transactions. This chapter explains the PostgreSQL object that identity columns use to generate numbers.
What a sequence does
A sequence is a database object that produces numbers one at a time. PostgreSQL stores the sequence separately from the table. An identity column uses a sequence internally, then applies the generated value to the column during an insert.
A sequence is useful when several sessions need new values without coordinating through the table. PostgreSQL can reserve the next value quickly, even when many clients insert rows at the same time.
Creating and using a sequence
This example creates a sequence explicitly and uses nextval as the column default. Identity syntax is usually clearer for new tables, but this example exposes the mechanism directly.
DROP TABLE IF EXISTS orders;
DROP SEQUENCE IF EXISTS order_id_seq;
CREATE SEQUENCE order_id_seq
START WITH 1
INCREMENT BY 1;
CREATE TABLE orders (
id bigint DEFAULT nextval('order_id_seq'::regclass) PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer)
VALUES ('Ada'), ('Grace')
RETURNING id, customer;nextval advances the sequence and returns its new value. Each call gets another value.
| Function or value | Meaning | Important detail |
|---|---|---|
| `nextval('order_id_seq')` | Advances and returns the next number | The sequence value is reserved immediately |
| `currval('order_id_seq')` | Returns this session's most recent value | This session must call `nextval` first |
| `setval('order_id_seq', 42)` | Sets the current sequence value | The next `nextval` normally returns 43 |
currval is session-specific. It does not mean “the last ID inserted into the table by anyone.” For example, after an insert in the same connection, you can use:
INSERT INTO orders (customer) VALUES ('Lin')
RETURNING id;
SELECT currval('order_id_seq'::regclass);The RETURNING clause is normally better because it gets the ID from the insert directly and supports multiple inserted rows.
Why sequence values are not transactional
Sequence operations are intentionally independent of transaction rollback. PostgreSQL does this to avoid making concurrent inserts wait for one another.
BEGIN;
INSERT INTO orders (customer) VALUES ('rolled back');
ROLLBACK;
INSERT INTO orders (customer) VALUES ('kept')
RETURNING id;The second insert may return 4 even though only two rows remain. The value used by the rolled-back insert is not reused. Gaps can also result from deleted rows, failed inserts, or cached values after a server restart.
Checking and changing a sequence
You can inspect or configure a sequence with SQL:
ALTER SEQUENCE order_id_seq
INCREMENT BY 10
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 20;Increasing CACHE can improve performance, but it can also make larger gaps possible after a crash. The sequence's limits must fit the type of the receiving column. A bigint column allows a much larger range than integer.
Exercise
If an insert calls nextval and then the transaction rolls back, what happens to that sequence value?
Show answer
The value remains consumed, so a later insert can receive a higher number and leave a gap.