Sub topic 10
Tuning start, increment and limits
This chapter assumes you can create an identity column, you know the difference between GENERATED ALWAYS and GENERATED BY DEFAULT, and you know the ranges of smallint, integer and bigint. It covers the options you can put in parentheses after AS IDENTITY. These options configure the hidden sequence that produces the values.
Where the options go
An identity column owns a sequence that PostgreSQL creates and names for you, such as tickets_id_seq. The parentheses after AS IDENTITY take the same options as CREATE SEQUENCE:
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1000 INCREMENT BY 10) PRIMARY KEY,
title text NOT NULL
);
INSERT INTO tickets (title) VALUES ('first'), ('second') RETURNING id;
-- id: 1000, 1010The options this chapter covers are START WITH, INCREMENT BY, MINVALUE, MAXVALUE, CACHE and CYCLE. You can also add SEQUENCE NAME to choose the sequence's name, but the other options are the ones that change behavior.
Defaults
If you leave an option out, PostgreSQL fills it in. For an ascending sequence the defaults are:
| Option | Default | Notes |
|---|---|---|
| `INCREMENT BY` | 1 | Cannot be 0. A negative value makes the sequence descending. |
| `MINVALUE` | 1 | The same as `NO MINVALUE`. |
| `MAXVALUE` | Largest value of the column type | 32767, 2147483647 or 9223372036854775807. |
| `START WITH` | `MINVALUE` | Must lie between `MINVALUE` and `MAXVALUE`. |
| `CACHE` | 1 | Values reserved per session at a time. |
| `CYCLE` | `NO CYCLE` | The sequence raises an error at its limit. |
The identity sequence takes its data type from the column. A smallint identity column therefore stops at 32767 without any extra option.
START WITH and MINVALUE
START WITH sets the first value the sequence returns. It does not change the lowest value the sequence may ever produce. That is MINVALUE, and it matters for cycling and for descending sequences.
If you set START WITH 1000 and leave MINVALUE alone, the minimum stays at 1. A later RESTART without a value goes back to 1000, because RESTART uses the recorded start value. A START WITH below MINVALUE, or above MAXVALUE, is rejected when you create the table.
Starting at a larger number is useful when the first IDs are reserved. Examples are low numbers kept for system rows, or an offset that makes IDs look consistent in a user interface. It is not a security measure. Anyone can still count upward.
INCREMENT BY
INCREMENT BY is the step between consecutive values. A common use is giving each of several writers its own residue class:
-- Node A produces 1, 3, 5, ...
CREATE TABLE events_a (
id bigint GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 2) PRIMARY KEY,
payload text
);
-- Node B produces 2, 4, 6, ...
CREATE TABLE events_b (
id bigint GENERATED ALWAYS AS IDENTITY (START WITH 2 INCREMENT BY 2) PRIMARY KEY,
payload text
);If the two tables are later merged, their IDs cannot collide. This only holds as long as the number of writers stays fixed. Adding a third node means changing the increment on the others, and that is hard to coordinate. For many independent writers, consider UUIDs instead (a later chapter).
A negative increment makes a descending sequence. The defaults then swap: MAXVALUE becomes -1, MINVALUE becomes the type's minimum, and the start is the maximum. A positive start value would fall outside that default range, so you must set MAXVALUE as well:
CREATE TABLE countdown (
n integer GENERATED ALWAYS AS IDENTITY
(INCREMENT BY -1 START WITH 3 MINVALUE 1 MAXVALUE 3) PRIMARY KEY,
label text
);
INSERT INTO countdown (label) VALUES ('a'), ('b'), ('c') RETURNING n;
-- n: 3, 2, 1MINVALUE and MAXVALUE
Set MAXVALUE when the ID space has a meaning, or when you want an early alarm. Without it, the sequence stops only at the type limit. When the sequence reaches its limit, the next nextval call fails and the insert is aborted:
CREATE TABLE raffle (
ticket smallint GENERATED ALWAYS AS IDENTITY (START WITH 1 MAXVALUE 3) PRIMARY KEY,
holder text NOT NULL
);
INSERT INTO raffle (holder) VALUES ('a'), ('b'), ('c');
INSERT INTO raffle (holder) VALUES ('d');
-- ERROR: nextval: reached maximum value of sequence "raffle_ticket_seq" (3)The error is explicit, which is better than silent corruption. It also means a busy table that hits its limit stops accepting rows until you raise the limit. That is why the choice of column type, covered in the previous chapter, matters before you tune limits.
CYCLE
With CYCLE, a sequence that reaches its limit wraps around. An ascending sequence returns to MINVALUE, and a descending one returns to MAXVALUE. The sequence itself stays quiet, but the table may not:
CREATE TABLE slots (
slot smallint GENERATED ALWAYS AS IDENTITY (MINVALUE 1 MAXVALUE 3 CYCLE) PRIMARY KEY,
label text
);
INSERT INTO slots (label) VALUES ('a'), ('b'), ('c');
INSERT INTO slots (label) VALUES ('d');
-- ERROR: duplicate key value violates unique constraint "slots_pkey"
DELETE FROM slots WHERE slot = 2;
INSERT INTO slots (label) VALUES ('e') RETURNING slot;
-- slot: 2The failed insert still consumed the value 1, so the sequence handed out 2 on the next attempt. Deleting the row with slot 2 freed the number, and the insert succeeded.
The flow of a single nextval call at the limit looks like this:
CACHE
By default, a session asks the sequence for one value at a time. With CACHE n, each session reserves n values in one step and hands them out from memory. This reduces contention on the sequence when many sessions insert at once.
The trade-offs are:
- Values are no longer in the order of insertion across sessions. If session A reserves 1 to 50 and session B reserves 51 to 100, session B's first row gets 51 while session A's later row gets 2.
- Each session's unused cached values are lost when it disconnects. This adds to gaps.
- A crash can also lose values, which is another way to get gaps.
A single-session workload sees no benefit from a larger cache. Leave CACHE at 1 unless you have measured contention on inserts. The IDs are not time-ordered, so never sort by ID to recover insertion order.
Inspecting the settings
The pg_sequences view shows what you configured. pg_get_serial_sequence returns the sequence's name for a given table and column, and it works for identity columns too:
SELECT pg_get_serial_sequence('tickets', 'id');
-- public.tickets_id_seq
SELECT sequencename, start_value, min_value, max_value,
increment_by, cycle, cache_size, last_value
FROM pg_sequences
WHERE sequencename = 'tickets_id_seq';
-- tickets_id_seq | 1000 | 1 | 2147483647 | 10 | f | 1 | (null until first use)last_value is null until the sequence has handed out its first value. It also reflects what a session has reserved, so with a cache it can be ahead of the largest ID in the table.
Changing options later
You can alter the sequence behind an identity column without recreating the table. Each option is changed with SET:
ALTER TABLE tickets ALTER COLUMN id SET MAXVALUE 1000000 SET CACHE 20;Changing START WITH this way does not move the sequence. It only changes where a later RESTART begins. Restarting and resynchronizing are covered in a later chapter.
Exercise
You create CREATE TABLE t (id smallint GENERATED ALWAYS AS IDENTITY (START WITH 100 INCREMENT BY 100) PRIMARY KEY);. Which values does the sequence hand out, and when does an insert first fail?
Show answer
It hands out 100, 200, 300, and so on, up to 32700. The next value would be 32800, which is above the smallint maximum of 32767, so the insert after 32700 fails with an error that the sequence reached its maximum value. The maximum comes from the column type, because the identity sequence takes its type from the column.
Exercise
A team sets CACHE 100 and CYCLE on an identity primary key to "never run out of IDs". Name two problems this causes.
Show answer
With CYCLE, the sequence wraps to MINVALUE after the limit and hands out numbers that may still be in use, so inserts fail with duplicate key errors. With CACHE 100, each session reserves 100 values at a time, so IDs are not in insertion order across sessions and the unused values of a session are lost when it disconnects, which makes gaps larger. A wider column type such as bigint is the correct way to avoid running out.