Search code examples
javapostgresqlservletsauto-increment

How to increment ID for each INSERT?


In PostgreSQL I have table comments with primary key comment_id (VARCHAR of length 4). I have a form to insert a comment. How to get my Java Servlet to increment comment_id for each INSERT (0001 to 0002)?


Solution

  • 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');