OVERRIDING SYSTEM VALUE Imports Identity Values

Import explicit IDs into GENERATED ALWAYS identity columns with OVERRIDING SYSTEM VALUE and contrast it with user value.

SqlData Integrity

Code

snippet
CREATE TABLE events (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL,
  imported_at timestamptz NOT NULL DEFAULT now()
);

-- GENERATED ALWAYS 默认拒绝显式 id;导入外部数据时必须声明覆盖
-- OVERRIDING SYSTEM VALUE imports explicit identity values
INSERT INTO events (id, name)
OVERRIDING SYSTEM VALUE
VALUES (42, 'legacy-import');

INSERT INTO events (name) VALUES ('generated');

-- OVERRIDING USER VALUE 相反:忽略传入值,改用序列
INSERT INTO events (id, name)
OVERRIDING USER VALUE
VALUES (999, 'sequence-wins');

SELECT id, name FROM events ORDER BY id;

-- 对照:不写 OVERRIDING 会报错
-- INSERT INTO events (id, name) VALUES (7, 'rejected');

-- 查看身份列绑定的序列及当前值
SELECT pg_get_serial_sequence('events', 'id') AS sequence_name;
SELECT last_value, is_called FROM events_id_seq;

How it works

Several statements share this file — SELECT / INSERT / CREATE, with events and events_id_seq among the objects involved.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

The events table is the working surface here.

Key statements

CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
imported_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO events (id, name)
OVERRIDING SYSTEM VALUE
VALUES (42, 'legacy-import');
INSERT INTO events (id, name)
OVERRIDING USER VALUE
VALUES (999, 'sequence-wins');

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`events`, `events_id_seq`.