Auto increment table column

后端 未结 4 1696
梦毁少年i
梦毁少年i 2020-11-22 02:35

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 Sta         


        
4条回答
  •  余生分开走
    2020-11-22 03:29

    Postgres 10 or later

    serial columns (see below) remain unchanged. But consider an IDENTITY column. Postgres 10 implements this standard-SQL feature.

    Basic syntax and info in the manual for CREATE TABLE.
    Detailed explanation in this blog entry of its primary author Peter Eisentraut.

    Create table with IDENTITY column

    CREATE TABLE staff (
       staff_id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
     , staff    text NOT NULL
    );

    Add IDENTITY column to existing table

    Table may or may not be populated with rows.

    ALTER TABLE staff ADD COLUMN staff_id int GENERATED BY DEFAULT AS IDENTITY;
    

    To also make it the PK at the same time (table can't have a PK yet):

    ALTER TABLE staff ADD COLUMN staff_id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY;
    

    Related:

    • How to add a PostgreSQL 10 identity column to an existing table with rows?

    Replace serial with IDENTITY column

    See:

    • How to change a table ID from serial to identity?

    Postgres 9.6 or older

    (Or any version, really.)
    Use the serial pseudo data type instead:

    CREATE TABLE staff (
       staff_id serial PRIMARY KEY,
     , staff    text NOT NULL
    );

    It creates and attaches the sequence object automatically and sets the DEFAULT to nextval() from the sequence. It does all you need.

    I used lower case identifiers in my example. Makes your life with Postgres easier.

提交回复
热议问题