Sub topic 2
Sequences: the mechanism underneath
Identity columns look like a column feature, but PostgreSQL implements them with a sequence. If you understand sequences, the behavior of identity columns (gaps, resets, out-of-order values) stops being surprising. This chapter covers the sequence object itself, its functions, and the rules it follows under concurrency and rollback.
This chapter assumes you can write CREATE TABLE, INSERT and SELECT, know what a primary key is, and know the basic idea of commit and rollback.
What a sequence is
A sequence is a database object that hands out numbers. Each call returns the next number in a series. It is a separate object from any table, like a view or an index, and it lives in a schema.
Internally, a sequence stores a small amount of state: the last value it handed out, and whether it has handed one out at all. The sequence itself does not know which tables use it. You connect a sequence to a column by making the column's default value call it.
Creating and using a sequence
This example creates a sequence that starts at 1000, then draws values from it:
CREATE SEQUENCE invoice_no START WITH 1000;
SELECT nextval('invoice_no'); -- 1000
SELECT nextval('invoice_no'); -- 1001
SELECT currval('invoice_no'); -- 1001Without options, a sequence uses these defaults:
| Option | Default for an ascending sequence |
|---|---|
| Data type | `bigint` |
| Start value | 1 |
| Increment | 1 |
| Minimum value | 1 |
| Maximum value | 9223372036854775807 (for `bigint`) |
| Cache size | 1 |
| Cycle | `NO CYCLE` |
You can choose a smaller type with AS smallint or AS integer. The type sets the maximum value, so an integer sequence stops at 2147483647.
The core functions
Three functions do almost all the work.
nextval(seq)advances the sequence and returns the new value. This is the only function that hands out a fresh number.currval(seq)returns the value thatnextvalmost recently returned in your own session.setval(seq, value [, is_called])sets the sequence's current position.
The argument is written as a quoted name, but its real type is regclass. PostgreSQL resolves the name to an object ID when it parses the statement. As a result, a default such as nextval('invoice_no') keeps working if you later rename the sequence. Schema-qualify the name ('billing.invoice_no') if the schema may not be on the search_path.
currval is per session
currval does not report the sequence's global state. It reports what your session last received. If your session has never called nextval on that sequence, currval raises an error:
SELECT currval('invoice_no');
-- ERROR: currval of sequence "invoice_no" is not yet defined in this sessionThis is deliberate. Other sessions can call nextval at any moment, so a global "current value" would be useless for finding the ID you just created. Because currval is per session, it is safe, but INSERT ... RETURNING is simpler and is covered in a later chapter. lastval() is a related function that returns the last nextval result in your session for any sequence. It is easy to misuse when triggers also call sequences, so prefer currval with an explicit name.
setval and the is_called flag
setval takes an optional third argument, is_called, which defaults to true. It controls what the next nextval returns:
SELECT setval('invoice_no', 5000); -- returns 5000
SELECT nextval('invoice_no'); -- 5001
SELECT setval('invoice_no', 7000, false); -- returns 7000
SELECT nextval('invoice_no'); -- 7000With is_called = true, PostgreSQL treats the value as already handed out, so the next call returns the following one. With false, the value counts as not yet handed out, so the next call returns it. A new sequence starts in the false state, which is why the first nextval returns the start value itself.
setval is how you repair a sequence after loading rows with explicit IDs. A later chapter covers that case. A value outside the sequence's minimum and maximum raises an error.
Sequences ignore transactions
Most database changes are rolled back when a transaction rolls back. Sequence changes are not:
SELECT nextval('invoice_no'); -- 7001
BEGIN;
SELECT nextval('invoice_no'); -- 7002
ROLLBACK;
SELECT nextval('invoice_no'); -- 7003, not 7002The value 7002 is gone. PostgreSQL does not give it back, and a later nextval will not reuse it.
This follows from how sequences work under concurrency. If a sequence were transactional, every session calling nextval would have to wait for the previous caller to commit or roll back. Instead, PostgreSQL applies each nextval immediately and permanently, and no session waits on another. Two concurrent transactions each get a distinct number at once.
The cost is that a sequence is not a gapless counter. Rollbacks, failed inserts and server crashes can all leave holes in the series. The "Why gaps happen" chapter goes through these cases. For now, remember the rule: a number handed out is never taken back.
Sequences are not guaranteed to be in order of commit
Because sessions take numbers independently, a number reflects when nextval was called, not when the transaction committed. Session A can take 10, session B can take 11, and B can commit first. A reader who looks at the table at that moment sees 11 but not 10. Do not use a sequence value to mean "everything below this has been committed". That assumption breaks incremental-export and change-detection code that polls for id > last_seen_id.
Connecting a sequence to a column
You can use a sequence as a column default by hand:
CREATE SEQUENCE ticket_no AS integer;
CREATE TABLE support_tickets (
id integer PRIMARY KEY DEFAULT nextval('ticket_no'),
title text NOT NULL
);
INSERT INTO support_tickets (title) VALUES ('Printer is on fire') RETURNING id;The default expression runs once for each inserted row where you do not supply id. Nothing links the sequence to the table, though. If you drop support_tickets, ticket_no stays behind. If you drop ticket_no while the default still refers to it, PostgreSQL refuses unless you use CASCADE. Ownership of a sequence by a column (ALTER SEQUENCE ... OWNED BY) fixes the first problem. The serial types and identity columns both set up this ownership automatically, which is a main reason to prefer them over hand-wired defaults.
Inspecting a sequence
The pg_sequences view lists each sequence with its settings and position:
SELECT sequencename, data_type, start_value, increment_by,
max_value, cache_size, cycle, last_value
FROM pg_sequences
WHERE sequencename = 'invoice_no';last_value is NULL if no session has called nextval on the sequence yet. You can also run SELECT * FROM invoice_no; to read the sequence's own state: the columns last_value, log_cnt and is_called. This is useful for diagnosis. Never use it as the way to get a new ID, because reading it does not advance anything.
To find the sequence behind a column, use pg_get_serial_sequence('support_tickets', 'id'). It works for serial and identity columns, and for sequences attached with OWNED BY.
Limits and what happens at the end
A sequence is bounded by its data type and its MAXVALUE. When nextval would pass the maximum, it fails:
CREATE SEQUENCE tiny AS smallint START WITH 32766;
SELECT nextval('tiny'); -- 32766
SELECT nextval('tiny'); -- 32767
SELECT nextval('tiny');
-- ERROR: nextval: reached maximum value of sequence "tiny" (32767)The sequence stops. It does not wrap around unless you created it with CYCLE, which would then hand out duplicates of old values. That is rarely what you want for a key. The sequence's type also does not have to match the column's type. A bigint sequence feeding an integer column works until the sequence passes 2147483647. At that point the insert fails with an integer out of range error. A later chapter on column types covers this mismatch.
Caching and crashes
Two further details affect the numbers you see.
- Cache. With
CACHE n, each session reserves a block ofnvalues at once and then serves them from memory. This is faster, but values a session reserved and never used are lost when it disconnects. Sessions also hold different blocks, so the numbers they hand out interleave in a less orderly way. The default of 1 means no preallocation. - Crash recovery. To avoid writing to the log on every call, PostgreSQL logs sequence state ahead of use, in advance of the values handed out. After a crash, the sequence can resume up to 32 values ahead of its last handed-out value. This creates a small gap and never causes a repeat.
Summary of the mechanism
| Question | Answer |
|---|---|
| Does rollback undo `nextval`? | No. |
| Can two sessions get the same value? | No, except after `CYCLE` wraparound or a backward `setval`. |
| Does `currval` see other sessions' values? | No, only your session's last `nextval`. |
| What does `setval(s, n)` make the next `nextval` return? | `n + 1` (or the increment-adjusted value). |
| What does `setval(s, n, false)` make the next `nextval` return? | `n`. |
| What happens at the maximum? | An error, unless `CYCLE` is set. |
Exercise
A sequence s has just returned 40 to your session. Another session has since called nextval('s') twice. You run SELECT setval('s', 100, false); and then SELECT nextval('s');. What does the second statement return, and what does currval('s') return in your session afterward?
Show answer
nextval returns 100, because is_called = false marks 100 as not yet handed out. currval('s') then also returns 100, because it reports the last value nextval returned in your session. The other session's calls do not affect it. Note that setval itself does not change what currval reports, but your later nextval call does.
Exercise
A transaction calls nextval('s') three times, inserts three rows using those values, and then rolls back. What state is the sequence in afterward, and what does the next nextval('s') return, if the last value before the transaction was 20?
Show answer
The rows are gone, but the sequence is not rolled back. It stays at 23, so the next nextval('s') returns 24. The values 21, 22 and 23 are never used.