Create postgresql sequence for database ids

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!
dimensionavAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Doug WaltonDatabase AdministratorCommented:
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.
earth man2Commented:
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;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PostgreSQL

From novice to tech pro — start learning today.