Skip to content

Instantly share code, notes, and snippets.

@scaryguy
Last active October 8, 2024 12:31
Show Gist options
  • Save scaryguy/6269293 to your computer and use it in GitHub Desktop.
Save scaryguy/6269293 to your computer and use it in GitHub Desktop.
How to change PRIMARY KEY of an existing PostgreSQL table?
-- Firstly, remove PRIMARY KEY attribute of former PRIMARY KEY
ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkey;
-- Then change column name of  your PRIMARY KEY and PRIMARY KEY candidates properly.
ALTER TABLE <table_name> RENAME COLUMN <primary_key_candidate> TO id;
-- Lastly set your new PRIMARY KEY
ALTER TABLE <table_name> ADD PRIMARY KEY (id);
@TechWithTy
Copy link

ty

@stetodd
Copy link

stetodd commented Feb 17, 2022

Thanks

@marcusflat
Copy link

Thanks a lot !!

@marcbachmann
Copy link

As @venriq mentioned, creating the new index first could be better.
Postgres could reuse other indexes during creation, if there's already one with the same columns.

I'm using that one to switch a multi column index:

ALTER TABLE <table_name> RENAME CONSTRAINT <table_name>_pkey TO <table_name>_pkeyold;
CREATE UNIQUE INDEX <table_name>_pkey ON <table_name> (id, namespace);
ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkeyold;
ALTER TABLE <table_name> ADD PRIMARY KEY USING INDEX <table_name>_pkey;

@Ramdelred
Copy link

thank you

@StephenFlavin
Copy link

worth noting that ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkey; does not drop the not null constraint on the column.

@matonga
Copy link

matonga commented Dec 21, 2023

@marcbachmann thank you! (didn't know postgres could reuse existing indices for newprimary keys, that's great)

@maksimugus
Copy link

thx, man! it's cool

@ToddEmonster
Copy link

Thank you !

@Pratapchandradeo
Copy link

Save the process bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment