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