PostgreSQL Autoincrement

Ian picture Ian · Apr 25, 2009 · Viewed 626.2k times · Source

I'm switching from MySQL to PostgreSQL and was wondering how I can do autoincrement values. I saw in the PostgreSQL docs a datatype "serial", but I get syntax errors when using it (in v8.0).

Answer

Trey picture Trey · Apr 25, 2009

Yes, SERIAL is the equivalent function.

CREATE TABLE foo (
id SERIAL,
bar varchar);

INSERT INTO foo (bar) values ('blah');
INSERT INTO foo (bar) values ('blah');

SELECT * FROM foo;

1,blah
2,blah

SERIAL is just a create table time macro around sequences. You can not alter SERIAL onto an existing column.