HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Change existing column in PG to auto-incremental primary key

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
primaryincrementalcolumnautoexistingchangekey

Problem

I have a database in Postgresql, which was migrated from SQL Server (only data).

On SQL Server, a table from this database has these columns:

measure_id
datum
measure


where measure_id is auto-incremental primary key, datum is datetime and measure is float.

After migration in Postrgresql, measure_id is column of type bigint.

How can I change this column (measure_id) to bigserial and assign it as primary key, now that my table is full of data?

Solution

Create a sequence and use it as the default value for the column:

create sequence measures_measure_id_seq
   owned by measures.measure_id;

alter table measures
   alter column measure_id set default nextval('measures_measure_id_seq');

commit;


That essentially what serial does.

See the manual for details:

http://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

Starting with Postgres 10, the recommended way is to use standard compliant identity columns, rather than serial (or bigserial).

alter table measures
   alter measure_id add generated always as identity;


In both cases, you will have to adjust the sequence to match the current maximum value in the measure_id column:

select setval(pg_get_serial_sequence('measures', 'measure_id'), max(measure_id))
from measures;

Code Snippets

create sequence measures_measure_id_seq
   owned by measures.measure_id;

alter table measures
   alter column measure_id set default nextval('measures_measure_id_seq');

commit;
alter table measures
   alter measure_id add generated always as identity;
select setval(pg_get_serial_sequence('measures', 'measure_id'), max(measure_id))
from measures;

Context

StackExchange Database Administrators Q#78732, answer score: 30

Revisions (0)

No revisions yet.