Skip to content

Instantly share code, notes, and snippets.

@scaryguy
Last active July 15, 2024 16:57
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);
@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

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