Skip to content

Instantly share code, notes, and snippets.

@estahn
Created October 4, 2013 13:10
Show Gist options
  • Select an option

  • Save estahn/6825645 to your computer and use it in GitHub Desktop.

Select an option

Save estahn/6825645 to your computer and use it in GitHub Desktop.
PostgreSQL - Add primary key to an existing Table
ALTER TABLE "public"."foo" ADD COLUMN "id" INTEGER;
CREATE SEQUENCE "public"."foo_id_seq";
UPDATE foo SET id = nextval('"public"."foo_id_seq"');
ALTER TABLE "public"."foo" ALTER COLUMN "id" SET DEFAULT nextval('"public"."foo_id_seq"');
ALTER TABLE "public"."foo" ALTER COLUMN "id" SET NOT NULL;
ALTER TABLE "public"."foo" ADD UNIQUE ("id");
ALTER TABLE "public"."foo" DROP CONSTRAINT "foo_id_key" RESTRICT;
ALTER TABLE "public"."foo" ADD PRIMARY KEY ("id");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment