Increment value of a table ID for each INSERT

后端 未结 2 367
南旧
南旧 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.

    0 讨论(0)
  • 2021-01-07 12:34

    You don't want to use a VARCHAR for your id column. In postgres you can create a sequence and then get the next value of that sequence for each insert.

    here are the docs

    Basically, you do something like

    CREATE SEQUENCE mysequence START 101
    

    Then, when you insert you do something like

    INSERT INTO my_comment values (nextval('mysequence'), 'this is my comment');
    
    0 讨论(0)
提交回复
热议问题