PostgreSQL 9.1 primary key autoincrement

Viewed 90341

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 Answers

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;
Related