Re: Switching identity column to serial

From: Peter Eisentraut <peter(dot)eisentraut(at)enterprisedb(dot)com>
To: Erik Wienhold <ewie(at)ewie(dot)name>, Ron <ronljohnsonjr(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Switching identity column to serial
Date: 2023-02-08 11:03:48
Message-ID: 87c8d1ad-e220-11db-8e3e-d66226feda74@enterprisedb.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 04.02.23 21:55, Erik Wienhold wrote:
>> Why doesn't this work?
>> BEGIN;
>> DROP SEQUENCE t_id;

[This won't work, you need to use ALTER TABLE / DROP IDENTITY.]

>> CREATE SEQUENCE new_t_id_seq AS INTEGER OWNED BY t.id;
>> ALTER SEQUENCE new_t_id_seq OWNER TO new_owner;
>> SELECT setval('new_t_id', (SELECT MAX(id) FROM t));
>> SELECT nextval('new_t_id');
>> COMMIT;
> This should work but I want to preserve the existing sequence instead of
> re-creating it with the same properties. That's why I was looking for a
> shortcut (also code golfing and sheer curiosity).

This is possible in principle, by implementing the inverse of the
"Upgrading" recipe from
<https://www.2ndquadrant.com/en/blog/postgresql-10-identity-columns/>.
But if you don't want to figure that out, I think dropping and
recreating the sequences as suggested here seems the best solution.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Eisentraut 2023-02-08 11:07:34 Re: Get the sequence name corresponding to a GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY column
Previous Message Laurenz Albe 2023-02-08 10:18:00 Re: How do a user-defined function that returns a table executes a query?