Sub topic 3
Tuning start, increment and limits
This chapter assumes you know CREATE TABLE, INSERT, primary keys, the integer types smallint, integer and bigint, and how COMMIT and ROLLBACK work. It covers how to set an identity column's numbering, why IDs skip numbers, and how to change identity columns safely.
Setting start, increment and limits
Identity options control the sequence behind the column:
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY
(START WITH 1000 INCREMENT BY 10 MAXVALUE 9999) PRIMARY KEY,
title text NOT NULL
);
INSERT INTO tickets (title) VALUES ('first'), ('second') RETURNING id;
-- ids: 1000, 1010MAXVALUE makes the sequence fail instead of wrapping. CYCLE makes it wrap around, which can produce duplicate keys, so avoid it for primary keys.
Why gaps happen
A sequence hands out each value once, and nothing returns it. Rollbacks, failed inserts and server crashes all consume values. Sequences are not transactional, so a rolled-back insert still uses its number:
BEGIN;
INSERT INTO tickets (title) VALUES ('rolled back');
ROLLBACK;
INSERT INTO tickets (title) VALUES ('kept') RETURNING id;
-- skips the number used by the rolled-back row> Identity values are unique and increasing, not gapless. Do not use them for invoice numbers that law requires to be consecutive.
Changing, restarting and dropping identity
Use ALTER TABLE to change an identity column:
ALTER TABLE tickets ALTER COLUMN id SET GENERATED ALWAYS;
ALTER TABLE tickets ALTER COLUMN id RESTART WITH 5000;
ALTER TABLE tickets ALTER COLUMN id DROP IDENTITY;Fixing the sequence after loading data
After you insert rows with explicit IDs, the sequence still starts from its old position. Move it past the largest existing ID:
SELECT setval(pg_get_serial_sequence('tickets', 'id'), max(id))
FROM tickets;Migrating a serial column to identity
Check the current maximum ID before you migrate. The example assumes it is 1000:
ALTER TABLE legacy ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE legacy_id_seq;
ALTER TABLE legacy ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 1001);When not to use sequential IDs
Sequential IDs reveal how many rows you have and their order. They also need a central sequence, which can complicate distributed systems. Consider UUIDs for IDs created on many servers or exposed to users. Use a natural key only when the value never changes.
Exercise
A transaction inserts a row into tickets, then rolls back. Does the next insert reuse the rolled-back ID?
Show answer
No. Sequences are not transactional, so the value stays consumed and the next insert gets the following number.