Adding serial type to a table

From: Scott Marlowe <scott(dot)marlowe(at)ihs(dot)com>
To: <pgsql-general(at)postgresql(dot)org>
Subject: Adding serial type to a table
Date: 2002-04-26 23:12:29
Message-ID: Pine.LNX.4.33.0204261706090.8484-100000@css120.ihs.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Someone needed to add a serial type to a table. Here's the quick dirty,
lazy dba way:

say table t1 has a structure like so:

create table t1 (field1 text, id int);

and data in it, and we want id to be a serial (autoincrementing etc...)
field.

do this:

create table t2 (field1 text, id serial);

Now, assuming that all the data in t1 has a unique id, we can just do
this:

insert into t2 (select * from t1);

and voila, our table is populated. One small problem, the current value
of the associate sequence is still set to the original number (1 I think).

So, we do this:

select setval('t2_id_seq',(select max(id) from t2));

And now we have our sequence ready to go.

Good luck!

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Risko Peter 2002-04-27 00:23:56 large object thx & vacuuming question
Previous Message Mike Castle 2002-04-26 22:30:28 Re: intel vs amd benchmark for pg server