Sub topic 2
Getting the new ID back with RETURNING
This section assumes you know basic CREATE TABLE and INSERT, what a primary key is, and the integer types smallint, integer, and bigint.
Getting the new ID back with RETURNING
When PostgreSQL generates an identity value, your application often needs it right away, for example to link a child row to its parent. Add RETURNING to the INSERT to get the generated value in the same round trip:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;Inserting explicit values with OVERRIDING
A GENERATED ALWAYS column rejects values you supply. To insert a specific ID, such as when restoring data, add OVERRIDING SYSTEM VALUE:
INSERT INTO orders (id, customer)
OVERRIDING SYSTEM VALUE
VALUES (100, 'Grace');Without the clause, PostgreSQL raises an error. Use this override sparingly, because it bypasses the sequence's protection against duplicates.
Adding a primary key: identity alone is not unique
An identity column generates values, but it does not enforce uniqueness. A PRIMARY KEY or UNIQUE constraint does that. This example uses GENERATED BY DEFAULT, so explicit values are allowed, and no key is defined:
CREATE TABLE t (
id integer GENERATED BY DEFAULT AS IDENTITY,
name text
);
INSERT INTO t (id, name) VALUES (1, 'a'), (1, 'b'); -- succeedsBoth rows are stored with id = 1. Add PRIMARY KEY to the column definition to reject the second row.
Choosing smallint, integer or bigint
The type sets the maximum value an identity can reach:
| Type | Maximum value | Use when |
|---|---|---|
| `smallint` | 32,767 | Small, fixed lookup tables |
| `integer` | 2,147,483,647 | Most tables with moderate growth |
| `bigint` | 9,223,372,036,854,775,807 | High-volume or long-lived tables |
If you omit the type, PostgreSQL uses integer. Choose bigint for tables that may exceed about 2 billion rows. Changing the type later requires a table rewrite, so decide early.
> Exercise
Exercise
Why does INSERT with an explicit id fail on a GENERATED ALWAYS column, and which clause allows it?
Show answer
ALWAYS forbids values other than the default. Adding OVERRIDING SYSTEM VALUE before VALUES permits the explicit id.