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)?

- 2,809
- 13
- 27
- 42

- 79
- 2
- 13
-
If you want to stick with varchar, you realize that with a length of 4 you aren't going to be able to handle more than 10k comments, right? – digitaljoel Nov 29 '12 at 22:25
2 Answers
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.
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');

- 26,265
- 15
- 89
- 115
Update: in Postgres 10 or later, consider an IDENTITY
column instead. See:
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
and smallserial
(in Postgres 9.2+). 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 target column list for an INSERT
command. If you later change table layout, your query 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 line of code). 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 manual here.

- 605,456
- 145
- 1,078
- 1,228