auto_increment columns in PostgreSQL
| October 23rd, 2008nothing new or special but certainly worth joting down
What’s done in MySQL with auto_increment statement in PosgteSQL is a bit more complicated. It requires creating a sequence first:
CREATE SEQUENCE exp_seq;
and then using it in table definition:
CREATE TABLE exp (id INT NOT NULL PRIMARY KEY DEFAULT nextval(‘exp_seq’), other varchar(30), created_at date);
Sequences are actually more powerfull than MySQL’s auto_increment as they have some interesting options. One of them is INCREMENT BY which can be very useful with some multiple master replication or multiple servers scenarios.
Operations allowed on sequences are: nextval, currval and setval.