Until now, each INSERT gave its own id. Two people can choose the same number, and somebody must know the last one. The database can give the numbers.
GENERATED ALWAYS AS IDENTITY
CREATE TABLE tickets (
id integer GENERATED ALWAYS AS IDENTITY,
subject text NOT NULL
);
INSERT INTO tickets (subject)
VALUES ('Lost parcel'), ('Wrong size'), ('Broken mug');tickets
| id | subject |
|---|---|
| 1 | Lost parcel |
| 2 | Wrong size |
| 3 | Broken mug |
An has a counter. Each new row gets the next number. Leave the column out of the INSERT.
ALWAYS refuses your numbers
ALWAYS means: only the database gives the value. An INSERT that gives an id fails:
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.GENERATED BY DEFAULT AS IDENTITY accepts a value from the INSERT and uses the counter only when the INSERT leaves the column out. The counter does not know about your values. If you insert id 1 by hand, the counter can still give 1 to the next row.
Gaps are normal
The counter never goes back. A number that it gives out is not given again:
An id says which row it is. It does not count the rows.
serial
Older PostgreSQL schemas use serial:
CREATE TABLE notes (id serial, body text);serial makes an integer column with a counter as its DEFAULT. It works like BY DEFAULT: an INSERT can give its own id. New schemas use GENERATED ALWAYS AS IDENTITY.