kid_drew
kid_drew

Reputation: 3995

Postgres - add sequential column to existing data

I have an existing table that currently doesn't have an id column and a lot of duplicate rows on what should be a unique pair - it's messy. Example:

 fips  | customer_id
-------+------------
 17043 |        2085
 17043 |        2085
 42091 |        4426
 42091 |        4426

customer_id/fips should be unique, but the current code and schema don't enforce that. There also isn't an id column, so I have no unique way to reference a single row.

I'd like to add an id column and assign sequential integers so I can have a unique primary key. How can I go about that?

Upvotes: 2

Views: 2045

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 656666

Postgres 10 added IDENTITY columns (as demonstrated in Gordon's answer).
In Postgres 9.6 (or any version) you can use use a serial column instead.

Either way, make it the PRIMARY KEY in the same command. That's cheaper for big tables:

ALTER TABLE tbl ADD COLUMN tbl_id serial PRIMARY KEY;

Or:

ALTER TABLE tbl ADD COLUMN tbl_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY;

db<>fiddle here

IDENTITY columns are not PRIMARY KEY automatically. Postgres allows multiple IDENTITY columns for the same table (even if that's rarely useful).

See:

Or you clean up the mess to make (fips, customer_id) unique. Then that can be your PK. See:

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1269723

You can simply add an identity column:

alter table t add column id int generated always as identity;

Here is a db<>fiddle.

Upvotes: 1

Related Questions