Skip to content

Instantly share code, notes, and snippets.

@dreadedhamish
Forked from scaryguy/change_primary_key.md
Created October 29, 2022 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreadedhamish/f9266a568f147236bdd9dad3ceea9099 to your computer and use it in GitHub Desktop.
Save dreadedhamish/f9266a568f147236bdd9dad3ceea9099 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment