How to invoke sequence while inserting new record into postgresql table?

How do I invoke a postgresql sequence while inserting new row into a table?

I want to do something like this:

insert into biz_term(
biz_term_id,
biz_term_name,
)
values(SELECT nextval(idsequence)',
'temp'
);

I want to do it because when I am trying to insert new record into biz_term table then sequence idsequence is not getting invoked directly. How to invoke it?

114181 次浏览

You got it almost. You don't need the SELECT in there:

insert into biz_term(
biz_term_id,
biz_term_name,
)
values(
nextval('idsequence'),
'temp'
);

Any reasons you did not specify the biz_term_id as serial (or bigserial) which handles that automatically for you?

Even though it's a bit old topic, I would like to point out that one good reason to go with BIGINT, against BIGSERIAL is if you are using hibernate. Here is the article: https://vladmihalcea.com/postgresql-serial-column-hibernate-identity/

As the article points out,

Using a SEQUENCE generator is a better alternative since the identifier can be generated prior to executing the INSERT statement

Posting an answer, cause i'm not yet eligible to comment :/ . I apologize in advance in case you find it inappropriate.