Monday, August 17, 2009

PostgreSQL AUTOINCREMENT field

Past few days i have been working on developing database for sport statistics.
Client demanded that we develop it on PostgreSQL.
I am kind of a mysql geek and I am used to work with auto increment fields, and PostgreSQL doesn't have
tipical autoincrement fields like MySQL has.
And all that was needed was this :

ALTER TABLE ourtable ADD ourid INT unsigned NOT NULL AUTO_INCREMENT_UNIQUE;

So we needed to find solution for this.

This is the procedure for creating "auto-increment" field in PostgreSQL.

First we have a table (lets name it ourtable), and we need to create cequence :

CREATE SEQUENCE ourtable_seq;

After creating cequence we are adding field to our table :

ALTER TABLE ourtable ADD ourid INT UNIQUE;

ALTER TABLE ourtable ALTER COLUMN ourid SET DEFAULT NEXTVAL('ourtable_seq');

And that's it. Everything that you insert after this last alter will have autoincrement on row ourid.
If for example you already have fields, that you previously inserted they don't have anything in ourid row, we need to
populate this :

UPDATE ourtable SET ourid = NEXTVAL('ourtable_seq');

That's it.

Next article will be how to speed up your application :)

No comments:

Post a Comment