Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL 9.1 primary key autoincrement

Tags:

sql

postgresql

I'm trying to add a primary key with an autoincrement.

I have read some docs and other questions - there're SERIAL and nextval() statements but it doesn't work.

Here's what I made:

CREATE TABLE IF NOT EXISTS "category" (   "id" integer SERIAL PRIMARY KEY,   "name" varchar(30) DEFAULT NULL ); // the error near "SERIAL" 

and

CREATE SEQUENCE your_seq; CREATE TABLE IF NOT EXISTS "category" (   "id" integer PRIMARY KEY nextval('your_seq'),   "name" varchar(30) DEFAULT NULL ); // the error near 'nextval' 

What do I wrong? I just want to increment the primary key by 1.

like image 886
WildDev Avatar asked Dec 26 '13 07:12

WildDev


People also ask

Is Autoincrement primary key?

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.

Is primary key auto increment by default Postgres?

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 .

Is there auto increment in PostgreSQL?

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.


2 Answers

serial is, more or less, a column type so saying integer serial is like saying text text, just say serial:

CREATE TABLE IF NOT EXISTS "category" (   "id" SERIAL PRIMARY KEY,   "name" varchar(30) DEFAULT NULL ); 

If you want to create the sequence yourself then you want to make the default value of id the next value in the sequence and that means saying default nextval('your_seq'):

CREATE SEQUENCE your_seq; CREATE TABLE IF NOT EXISTS "category" (   "id" integer PRIMARY KEY default nextval('your_seq'),   "name" varchar(30) DEFAULT NULL ); 

To simulate the usual serial behavior you'll also want to make the sequence owned by the table:

alter sequence your_seq owned by category.id; 

Reading the Serial Types section of the manual might be fruitful.


I'd also recommend that you don't double quote your table and column names unless you have to. PostgreSQL will fold your identifiers to lower case so id and "id" will be the same thing but unnecessary quoting is a bad habit that can easily lead to a big mess of quotes everywhere.

like image 173
mu is too short Avatar answered Sep 27 '22 19:09

mu is too short


If someone needs to modify an existing table to add a primary key with auto-increment:

ALTER TABLE table_name ADD COLUMN pk_column_name SERIAL PRIMARY KEY; 
like image 24
Valentin Podkamennyi Avatar answered Sep 27 '22 17:09

Valentin Podkamennyi