37

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 neither of them 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 am I doing wrong? Is there a way to increment the primary key by 1.

2
  • 4
    You are defining "id" as INTEGER then SERIAL. SERIAL is a data type. PostgreSQL will create a SEQUENCE for you. You just need to remove INTEGER.
    – user2839610
    Dec 26, 2013 at 7:50
  • The table was filled with data before adding PK ? Nov 28, 2014 at 22:24

2 Answers 2

95

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.

2
  • How to define not null in serial and primary field ? Id INT NOT NULL SERIAL PRIMARY KEY is right ?
    – Shesha
    Jun 30, 2016 at 5:15
  • @Shesha: id serial not null primary key. serial is, more or less, a column type that takes care of the int and default nextval... stuff for you. Jun 30, 2016 at 5:47
5

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.