Sub topic 7
Inserting explicit values with OVERRIDING
This chapter assumes you can write CREATE TABLE and INSERT statements and know what a primary key is. It also assumes you know the difference between GENERATED ALWAYS and GENERATED BY DEFAULT, covered in the previous chapter. It covers the two OVERRIDING clauses of INSERT, what they do in each generation mode, and the sequence problems that explicit values cause.
Why you sometimes need to supply the ID
Most inserts should leave an identity column alone and let PostgreSQL generate the value. Some jobs need to control the ID:
- Restoring a dump or copying rows between databases, where other tables refer to the existing IDs.
- Loading reference data with fixed IDs, such as status code
1 = active. - Reserving a sentinel row, such as
id = 0for "unknown". - Copying rows into a table that should assign fresh IDs, even though the source query returns old ones.
A GENERATED ALWAYS column is built to make this hard to do by accident. The OVERRIDING clauses are the deliberate way around that.
What GENERATED ALWAYS rejects
Start with a table whose identity column is GENERATED ALWAYS:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada');The first row gets id = 1. Now try to supply an ID yourself:
INSERT INTO orders (id, customer) VALUES (100, 'Grace');
-- ERROR: cannot insert a non-DEFAULT value into column "id"
-- DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
-- HINT: Use OVERRIDING SYSTEM VALUE to override.The error names the word "non-DEFAULT" because the keyword DEFAULT is allowed. Writing DEFAULT for the column means "generate the value", so this statement works:
INSERT INTO orders (id, customer) VALUES (DEFAULT, 'Linus') RETURNING id;It returns 2. This is useful in generated SQL and in multi-row inserts where some rows supply an ID and others do not.
OVERRIDING SYSTEM VALUE
OVERRIDING SYSTEM VALUE tells PostgreSQL to accept the values you supply for identity columns, even GENERATED ALWAYS ones. The clause goes after the column list and before VALUES or the SELECT:
INSERT INTO orders (id, customer)
OVERRIDING SYSTEM VALUE
VALUES (100, 'Grace');The row is stored with id = 100. A few details matter:
- The clause applies to the whole statement. Every row in a multi-row insert uses the values you give, so you cannot mix supplied and generated IDs for one column, except by writing
DEFAULTin individual rows. - If you leave the identity column out of the column list, the sequence still generates the value. The clause only affects columns you list.
- On a
GENERATED BY DEFAULTcolumn, the clause changes nothing, because explicit values are already accepted.
The name "system value" refers to the generated value. The clause means "override the system's generated value with mine."
OVERRIDING USER VALUE
OVERRIDING USER VALUE does the opposite. PostgreSQL ignores any value you supply for an identity column and generates one from the sequence. This works for both ALWAYS and BY DEFAULT columns.
It is mainly useful in INSERT ... SELECT, where the source query returns old IDs that you do not want. Here is a copy of orders that assigns its own IDs:
CREATE TABLE orders_copy (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders_copy (id, customer)
OVERRIDING USER VALUE
SELECT id, customer FROM orders;
SELECT id, customer FROM orders_copy ORDER BY id;The result has IDs 1, 2 and 3, not the original 1, 2 and 100. Without the clause, the insert would fail on the GENERATED ALWAYS column. The clause lets you write a column list that mirrors the source table without special-casing the ID.
How the clauses compare
| What you write | `GENERATED ALWAYS` column | `GENERATED BY DEFAULT` column |
|---|---|---|
| Explicit value, no clause | Error | Value stored |
| `DEFAULT` keyword | Generated value | Generated value |
| `OVERRIDING SYSTEM VALUE` with explicit value | Value stored | Value stored |
| `OVERRIDING USER VALUE` with explicit value | Generated value, yours ignored | Generated value, yours ignored |
| Column omitted from the list | Generated value | Generated value |
The sequence does not notice
Supplying an explicit ID does not move the sequence. The sequence has no idea that you stored 100, so it keeps counting from where it was. Consider a BY DEFAULT table:
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title text NOT NULL
);
INSERT INTO tickets (id, title) VALUES (2, 'imported');
INSERT INTO tickets (title) VALUES ('a') RETURNING id;
INSERT INTO tickets (title) VALUES ('b') RETURNING id;The first generated insert returns 1. The second tries to use 2, which is taken, and fails:
ERROR: duplicate key value violates unique constraint "tickets_pkey"
DETAIL: Key (id)=(2) already exists.The failed attempt still consumed the sequence value, so a retry gets 3. This is the same effect as the gaps discussed later in the tutorial. The real problem is that the sequence is now behind the data, and the primary key is the only thing that catches it. If the column had no uniqueness constraint, you would silently get duplicate IDs.
The same thing happens with OVERRIDING SYSTEM VALUE on a GENERATED ALWAYS column. The clause lets you in, but it does not tidy up afterwards.
If the loaded IDs are all higher than anything the sequence will reach soon, collisions appear later, not immediately. That makes the bug harder to trace to the load.
Where OVERRIDING does not apply
The clauses belong to INSERT only. They have no effect on other statements:
UPDATE orders SET id = 5 WHERE id = 1fails on aGENERATED ALWAYScolumn. The only allowed assignment there isSET id = DEFAULT, which assigns a new value from the sequence.- On a
GENERATED BY DEFAULTcolumn,UPDATEcan set any value, subject to the primary key. - To change an
ALWAYScolumn by hand, you must first change its mode withALTER TABLE ... ALTER COLUMN ... SET GENERATED BY DEFAULT.
Restore tools use the same mechanism. A dump made with pg_dump --column-inserts writes OVERRIDING SYSTEM VALUE in its INSERT statements for GENERATED ALWAYS columns, so reloading it keeps the original IDs.
Choosing between the approaches
Think about who is allowed to set IDs, and how often.
- If IDs should never be set by application code, use
GENERATED ALWAYS. Occasional loads and repairs useOVERRIDING SYSTEM VALUE, and each use is visible in the SQL and in code review. - If many clients or tools routinely supply IDs, use
GENERATED BY DEFAULT. You avoid writing the clause everywhere, but nothing stops a careless insert from supplying an ID. - If you copy rows from a table with its own IDs and want new ones, use
OVERRIDING USER VALUErather than leaving the ID out of both lists. It lets you keep a column list identical on both sides.
Common mistakes
- Putting the clause in the wrong place. It must come after the column list and before
VALUESorSELECT. Placing it afterVALUES (...)is a syntax error. - Expecting
OVERRIDING USER VALUEto raise an error when you supply a value. It silently discards the value. - Forgetting that
OVERRIDING SYSTEM VALUEdoes not update the sequence. - Omitting the identity column from the column list and still expecting your IDs to be stored. Without the column in the list, there is nothing to override.
Exercise
A table items has id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY. You run INSERT INTO items (id, name) OVERRIDING USER VALUE VALUES (50, 'bolt') RETURNING id; on an empty table. What id is returned, and why? Then, what single change to the statement stores 50 instead?
Show answer
It returns 1. OVERRIDING USER VALUE ignores the supplied 50 and takes the next value from the sequence, without raising an error. Replacing it with OVERRIDING SYSTEM VALUE stores 50. After that, the sequence is still at its start, so the next generated insert returns 1 and later reaches 50, where it collides with the stored row unless you resynchronize the sequence.
Exercise
You load 1,000 rows with IDs 1 to 1000 into an empty GENERATED BY DEFAULT table using explicit IDs. The next insert without an ID fails with a duplicate key error. Why did it fail, and which value does the following attempt receive?
Show answer
The explicit inserts never advanced the sequence, so it still started at 1 and handed out 1, which already exists. The failed attempt consumed that sequence value, so the next attempt gets 2, and keeps failing until the sequence passes 1000. The fix is to set the sequence to the maximum stored ID before inserting without IDs.