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:


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?


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');


That essentially what serial does.

See the manual for details:

  • Ok, thanks. Can you just drop a note what does owned by measures.measure_id do?
    – zetah
    Oct 9 '14 at 6:06
  • @zetah: Quote from the manual (the link I added): "the sequence is marked as "owned by" the column, so that it will be dropped if the column or table is dropped" Oct 9 '14 at 6:11
  • 2
    Ah, all right it's just like a decoration. I mentioned that table already has data, but newly created sequence wont respect already present data and will start counting from 1, which will error on first new insert for unique constraint. So if anyone else is reading this it's more correct to use CREATE SEQUENCE seq START WITH x where x is last row (SELECT MAX(measure_id)+1 FROM measures in my case)
    – zetah
    Oct 9 '14 at 6:23
  • 1
    @zetah Thanks for this update. How would you write a query in that case? I tried CREATE SEQUENCE seq START WITH (SELECT MAX(measure_id)+1 FROM measures); but this does not seem to be the correct way. Mar 1 '16 at 11:46
  • What you're trying to do is : select setval('sequenceX', (select max(table_id)+1 from table), false) Found here : stackoverflow.com/questions/2022559/…
    – HydrUra
    Apr 26 '19 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.