Eli Kara wrote:

create table foo ( serial bar primary key, ...




That does NOT work on my PostgreSQL 7.4.3. What DOES work is: (assuming you have table foo)

ALTER TABLE foo ADD COLUMN id int;    // create an 'id' field, integer
CREATE SEQUENCE foo_id_seq;               // create an auto-incrementing seq.
ALTER TABLE foo ALTER COLUMN id SET DEFAULT nextval('foo_id_seq');
// set the default value of 'id' to be the next value in the sequence
UPDATE foo SET id = nextval('foo_id_seq');  // update existing 'id' column

Am I missing some simpler way ? I remember googling about this for quite some time and that is the solution I found.

Regards,
Eli



sun=# create table foo ( bar serial primary key );
NOTICE: CREATE TABLE will create implicit sequence "foo_bar_seq" for "serial" column "foo.bar"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
CREATE TABLE


Now, if you want to add a serial retroactively, then you will have to do what you mention. This has to do with the fact that you cannot add a column and set a default value to it in one go, and the "Serial" type is really just syntactic sugar to what you want to do.

Then again, this is just syntactic sugar to a rather uncommon operation. Is that really such a problem?

            Shachar
P.S.
I prefer to be CCed on messages sent to the list.

--
Shachar Shemesh
Lingnu Open Source Consulting ltd.
http://www.lingnu.com/


================================================================= To unsubscribe, send mail to [EMAIL PROTECTED] with the word "unsubscribe" in the message body, e.g., run the command echo unsubscribe | mail [EMAIL PROTECTED]



Reply via email to