Sub topic 3
The older serial approach
This chapter assumes you can write basic CREATE TABLE and INSERT statements and know what a primary key is. You should also know the integer types smallint, integer and bigint. The previous chapter introduced sequences and nextval. This chapter shows how serial builds on them, so that you can read, maintain and later migrate the many schemas that still use it.
What serial is
Before PostgreSQL 10 added GENERATED AS IDENTITY, serial was the usual way to get an auto-incrementing column. It is not a real data type. It is shorthand that the parser expands into several separate objects when you run CREATE TABLE.
| Declared type | Alias | Real column type | Sequence maximum |
|---|---|---|---|
| `smallserial` | `serial2` | `smallint` | 32,767 |
| `serial` | `serial4` | `integer` | 2,147,483,647 |
| `bigserial` | `serial8` | `bigint` | 9,223,372,036,854,775,807 |
The sequence is created with the same range as the column type, so an overflowing serial column fails with a sequence error and not a type error.
What the shorthand expands to
This statement uses serial:
CREATE TABLE invoices (
id serial PRIMARY KEY,
note text NOT NULL
);PostgreSQL treats it as if you had written the following:
CREATE SEQUENCE invoices_id_seq AS integer;
CREATE TABLE invoices (
id integer NOT NULL DEFAULT nextval('invoices_id_seq') PRIMARY KEY,
note text NOT NULL
);
ALTER SEQUENCE invoices_id_seq OWNED BY invoices.id;Three things happen:
- A sequence named
<table>_<column>_seqis created. PostgreSQL shortens the name if it is too long, and adjusts it if the name is already taken. - The column gets
NOT NULLand a default ofnextval('<sequence>'). - The sequence is marked as owned by the column, so dropping the column or table also drops the sequence.
Notice what serial does not add. It does not make the column unique or a primary key. In the examples here the PRIMARY KEY clause is what provides uniqueness, exactly as it does for identity columns.
Seeing the expansion in the catalog
Because the pieces are ordinary objects, you can inspect them with ordinary queries.
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'invoices' AND column_name = 'id';
SELECT pg_get_serial_sequence('invoices', 'id');The first query shows column_default as nextval('invoices_id_seq'::regclass). The second returns public.invoices_id_seq. The function pg_get_serial_sequence works for both serial and identity columns, which is why the resynchronization recipe later in this tutorial works with either.
In psql, \d invoices shows the same default in the column list. An identity column shows generated always as identity there instead.
Inserting and the DEFAULT behavior
Since the sequence is wired in through a column default, the usual insert pattern is to leave the column out:
INSERT INTO invoices (note) VALUES ('first') RETURNING id;The default fires, nextval returns 1, and RETURNING hands it back. This is the same flow you learned for identity columns.
The important difference is that a default is only a default. Any client can supply its own value, and PostgreSQL accepts it without complaint. A serial column therefore behaves like GENERATED BY DEFAULT, and there is no equivalent of GENERATED ALWAYS.
INSERT INTO invoices (id, note) VALUES (2, 'manual');
INSERT INTO invoices (note) VALUES ('auto');
-- ERROR: duplicate key value violates unique constraint "invoices_pkey"
-- DETAIL: Key (id)=(2) already exists.The manual insert used ID 2 but did not touch the sequence. The next automatic insert asked the sequence for its next value, got 2, and collided. (If the table already had a row with ID 1, the failing value would be the one the sequence returned.) The usual fix is to move the sequence forward with setval, shown later in this tutorial. A failed insert still consumes a sequence value, so the sequence moves on and the next attempt would get 3.
Problems that led to identity columns
The serial design works, but the pieces are loosely joined. Four weaknesses are worth knowing, because each is a bug you may meet in a real database.
The sequence needs its own permissions
The default calls nextval, and calling nextval requires USAGE on the sequence. Granting INSERT on the table is not enough.
GRANT INSERT ON invoices TO app_user;
-- app_user now runs: INSERT INTO invoices (note) VALUES ('x');
-- ERROR: permission denied for sequence invoices_id_seq
GRANT USAGE ON SEQUENCE invoices_id_seq TO app_user;With an identity column, the table privilege is sufficient, because the sequence belongs to the column's identity and is not a separately granted object.
Copying a table can share the sequence
LIKE ... INCLUDING DEFAULTS copies the column default text, and that text names the original sequence.
CREATE TABLE invoices_archive (LIKE invoices INCLUDING DEFAULTS);Now invoices_archive.id also calls nextval('invoices_id_seq'). Both tables draw from one sequence. Inserts into either table create gaps in the other, and dropping the original table fails or leaves the copy without a default, depending on how ownership was set. For identity columns, INCLUDING IDENTITY creates a new sequence for the copy.
Ownership can be broken
The OWNED BY link is a separate setting. If someone creates a sequence by hand and points a default at it, or runs ALTER SEQUENCE ... OWNED BY NONE, dropping the table leaves an orphaned sequence behind. Dropping the sequence while the default still names it breaks the next insert with a "relation does not exist" error, unless you use DROP SEQUENCE ... CASCADE, which removes the default as well.
It is not standard SQL
serial is a PostgreSQL feature. GENERATED ... AS IDENTITY is part of the SQL standard, and other database systems implement it. Tools that read your schema, and anyone moving between databases, will find identity easier to work with.
Where serial still appears
You will meet serial in three places:
- Older schemas, and dumps produced by older tools.
pg_dumpwrites a serial column as anintegercolumn with anextvaldefault, a separateCREATE SEQUENCEand anALTER SEQUENCE ... OWNED BY. - Code generators and ORMs that predate PostgreSQL 10, or that still default to
serial. - Tutorials and Stack Overflow answers written before 2017.
serial is not deprecated, and existing columns keep working. For new tables, prefer identity columns. For existing tables, a later chapter shows how to convert them.
A short checklist for a serial column
When you inherit a table with a serial column, check these points:
- The sequence exists and is owned by the column.
pg_get_serial_sequencereturns a name if it is. - The sequence type matches the column type. A
bigserialcolumn with an integer sequence will overflow at 2,147,483,647 even though the column could hold more. - The sequence is ahead of
max(id), particularly after data loads or manual inserts. - Application roles have
USAGEon the sequence. - No other table's default points at the same sequence, unless that is intended.
Exercise
A table was created with id serial PRIMARY KEY. An import script inserted rows with explicit IDs 1 through 500, and now ordinary inserts that omit id fail with a duplicate key error. Why does this happen, and why would GENERATED ALWAYS AS IDENTITY have prevented the situation?
Show answer
The explicit IDs bypassed the column default, so the sequence never advanced and still returns 1, 2, 3, and so on, which already exist in the table. A serial column behaves like GENERATED BY DEFAULT and accepts any supplied value. A GENERATED ALWAYS identity column would have rejected the import's explicit IDs (unless the script used OVERRIDING SYSTEM VALUE), making the problem visible at load time.
Exercise
You grant INSERT on a serial-based table to a new role, but its inserts fail with "permission denied for sequence". What single statement fixes this, assuming the sequence is orders_id_seq and the role is app_user?
Show answer
GRANT USAGE ON SEQUENCE ordersidseq TO app_user; The column default calls nextval, which needs USAGE on the sequence in addition to INSERT on the table.