Created
April 10, 2023 11:16
-
-
Save jianhe-fun/bc328e4095a946842bfe9a5fb348b8e7 to your computer and use it in GitHub Desktop.
convert unique index to primary key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--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