Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Autoincrement

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).

like image 315
Ian Avatar asked Apr 24 '09 22:04

Ian


People also ask

Does Postgres have Autoincrement?

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.

Does Postgres auto-increment primary key?

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 .

What is Autoincrement?

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.


1 Answers

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.

like image 191
Trey Avatar answered Sep 19 '22 08:09

Trey