Skip to content

Instantly share code, notes, and snippets.

@Bondifrench
Created May 6, 2014 22:49
Show Gist options
  • Save Bondifrench/46841e8a859104735762 to your computer and use it in GitHub Desktop.
Save Bondifrench/46841e8a859104735762 to your computer and use it in GitHub Desktop.
Adding primary key to existing table in Postgres
#!/usr/bin/env SQL
#Lets say you have a sec_sample table to which you want to add a id (surrogate) autoincremental PK:
ALTER TABLE sec_sample ADD column id serial;
UPDATE sec_sample SET id = nextval(pg_get_serial_sequence('sec_sample', 'id'));
ALTER TABLE sec_sample ADD PRIMARY KEY (id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment