From: Thomas Kellerer <spam_eater@gmx.net>
To: pgsql-general@lists.postgresql.org
Subject: Re: Resetting identity columns
Date: Mon, 22 Apr 2019 21:38:39 +0200
Message-ID: <f0ea89b2-815a-0d8d-da44-6e0d84ea255e@gmx.net> (raw)
In-Reply-To: <5db0ed5c-00ba-65fa-92f0-7e02c1495d18@rodonnell.ie>
References: <5db0ed5c-00ba-65fa-92f0-7e02c1495d18@rodonnell.ie>
Ray O'Donnell schrieb am 22.04.2019 um 17:30:
> I'm probably doing something silly.... I'm migrating data from one
> database table to another, where the old table used a SERIAL primary
> key and the new one uses GENERATED BY DEFAULT AS IDENTITY. Having
> loaded the data into the new table, I need to reset the underlying
> sequence so that it picks up from the highest existing value.
>
> I'm using PostgreSQL 11.2 on Debian 9.
>
> I've tried:
>
> =# alter table orders alter column order_id restart with (
> select max(order_id) + 1 from orders);
>
> ERROR: syntax error at or near "("
> LINE 1: ...r table orders alter column order_id restart with (select ma...
>
>
> What am I missing?
>
> I should add that this is part of a larger migration script; otherwise I could just do it by hand the command line.
As you noticed, an identity column is backed by a sequence, just like a serial column, so you can use setval() to sync the sequence.
To get the name of the sequence you can also use pg_get_serial_sequence() (despite its name):
select setval(pg_get_serial_sequence('orders', 'order_id'), (select max(order_id) from x));
Thomas
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: spam_eater@gmx.net
Subject: Re: Resetting identity columns
In-Reply-To: <f0ea89b2-815a-0d8d-da44-6e0d84ea255e@gmx.net>
References: <5db0ed5c-00ba-65fa-92f0-7e02c1495d18@rodonnell.ie> <f0ea89b2-815a-0d8d-da44-6e0d84ea255e@gmx.net>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox