Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jianhe-fun/bc328e4095a946842bfe9a5fb348b8e7 to your computer and use it in GitHub Desktop.
Save jianhe-fun/bc328e4095a946842bfe9a5fb348b8e7 to your computer and use it in GitHub Desktop.
convert unique index to primary key
--https://dba.stackexchange.com/questions/324803/add-composite-primary-key-on-existing-postgresql-table/324815#324815
CREATE TABLE demo (
a int,
b int,
CONSTRAINT a_b UNIQUE (a, b)
);
INSERT INTO demo VALUES (1, 2),(2, 3);
------------------------------------------------------
ALTER TABLE public.demo
ALTER COLUMN a SET NOT NULL,
ALTER COLUMN b SET NOT NULL;
-- must run on its own:
CREATE UNIQUE INDEX CONCURRENTLY a_b_temp ON demo (a, b);
ALTER TABLE demo
DROP CONSTRAINT a_b,
ADD CONSTRAINT demo_pkey PRIMARY KEY USING INDEX a_b_temp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment