Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stellingsimon/c502389543834671cf283b01d7a2a781 to your computer and use it in GitHub Desktop.
Save stellingsimon/c502389543834671cf283b01d7a2a781 to your computer and use it in GitHub Desktop.
Postgres unique constraints are checked immediately not at the end of the statement
CREATE TABLE test (
val TEXT,
sort_order INTEGER NOT NULL UNIQUE
);
-- works fine:
TRUNCATE test;
INSERT INTO test
VALUES ('B', 2),
('A', 1);
UPDATE test
SET sort_order = sort_order + 1;
-- UPDATE fails:
TRUNCATE test;
INSERT INTO test
VALUES ('A', 1),
('B', 2);
UPDATE test
SET sort_order = sort_order + 1;
-- result:
-- ERROR: duplicate key value violates unique constraint "test_sort_order_key"
-- Detail: Key (sort_order)=(2) already exists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment