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).
PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases.
By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With