Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mknparreira/e7c5e981c9f8164037a9a1ae45c557a8 to your computer and use it in GitHub Desktop.
Save mknparreira/e7c5e981c9f8164037a9a1ae45c557a8 to your computer and use it in GitHub Desktop.
PostgreSQL | Add an auto-incrementing primary key to an existing table

MORDERN VERSIONS

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

OLD VERSIONS

 ALTER TABLE test1 ADD COLUMN id INTEGER;
  CREATE SEQUENCE test_id_seq OWNED BY test1.id;
  ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
  UPDATE test1 SET id = nextval('test_id_seq');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment