Create postgresql sequence for database ids

dimensionav
dimensionav used Ask the Experts™
on
Hi!

We imported a MySQL database and, since in postgre there isn't Autoincrement options, we need to create a serial.

The thing is, the current exported id's doesn't allow us to change its type from int to a serial, instead of  that, Postgresql is asking to create a sequence and set the default value as the nextval of that sequence

Is there any more efficient way to do it?

Regards!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Doug WaltonDatabase Administrator

Commented:
As far as I know, that's the only way to do it which is kind of annoying.

If you have to do this a ton of times you could try creating a procedure that would take a table and column name as parameters that would do it for you.
say you have a table called tablename and the column you want to be the autoincrement id called colname.

It is not more efficient to do this any different way type serial is equivalent to ...

CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (colname integer NOT NULL DEFAULT nextval('tablename_colname_seq'));


after the fact creating an autoincrement key on an existing table...
CREATE SEQUENCE tablename_colname_seq ;
ALTER TABLE tablename ALTER COLUMN colname SET DEFAULT nextval('tablename_colname_seq');
generally you would set it to be the primary key and set the sequence ownership....
ALTER SEQUENCE tablename_colname_seq RESTART WITH (select max(colname)+1 from tablename) OWNED BY tablename.colname;
CREATE UNIQUE INDEX tablename_pk ON tablename(colname);
ALTER TABLE tablename ADD PRIMARY KEY USING INDEX tablename_pk;

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial