Increment value of a table ID for each INSERT

后端 未结 2 366
南旧
南旧 2021-01-07 12:00

I\'m using PostgreSQL with all my tables setup. I currently have a table called comments with a primary key called comment_id which is a VARC

2条回答
  •  执念已碎
    2021-01-07 12:26

    Use the serial pseudo data type to begin with. It creates and attaches the sequence object automatically and sets the DEFAULT to nextval() from the sequence. It does all you need. Effective type for the column is integer. There is also bigserial. Just follow the link to the manual.

    CREATE TABLE comments (
        comment_id serial PRIMARY KEY
       ,comment text NOT NULL
       );
    

    You can ignore the column for INSERT commands:

    INSERT INTO my_comment (comment)
    VALUES ('My comment here');
    

    comment_id is filled in automatically.
    But you should always provide a column list for INSERT. If you later change table layout, your code may break in hurtful ways. It may be ok to skip the column list for ad-hoc commands or when the table structure is guaranteed (like when you created the table in the same transaction). Other than that, provide a column list!

    If you want the resulting comment_id back, without another round trip to the server:

    INSERT INTO my_comment (comment)
    VALUES ('My comment here');
    RETURNING comment_id;

    Details in the excellent manual here.

提交回复
热议问题