Using Postgres, I’m trying to use AUTO_INCREMENT to number my primary key automatically in SQL. However, it gives me an error.
CREATE TABLE Staff (
ID INTEGER NOT NULL AUTO_INCREMENT,
Name VARCHAR(40) NOT NULL,
PRIMARY KEY (ID)
);
The error:
********** Error ********** ERROR: syntax error at or near "AUTO_INCREMENT" SQL state: 42601 Character: 63
Any idea why?
Postgres 10 or later
Consider a standard-SQL
IDENTITYcolumn.serialcolumns remain unchanged. (See below.) But the former is preferable in modern Postgres. Can beGENERATED BY DEFAULTor (stricter)GENERATED ALWAYS.Basics in the manual for
CREATE TABLE.Details in this blog entry by its principal author Peter Eisentraut.
Create table with
IDENTITYcolumnAdd
IDENTITYcolumn to existing tableTable may or may not be populated with rows.
To also make it the PK at the same time (table can’t have a PK yet):
See:
Replace
serialwithIDENTITYcolumnSee:
You can override system values or user input in
INSERTcommands withOVERRIDING {SYSTEM|USER} VALUE.Postgres 9.6 or older
(Still supported in newer versions, too.)
Use the
serialpseudo data type:It creates and attaches the sequence object automatically and sets the
DEFAULTtonextval()from the sequence. It does all you need.I use legal, lower-case, unquoted identifiers in my examples. Makes your life with Postgres easier.