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

PostgresqlPostgresql 9.1

Postgresql Problem Overview


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?

Postgresql Solutions


Solution 1 - Postgresql

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?

Solution 2 - Postgresql

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajeshView Question on Stackoverflow
Solution 1 - Postgresqla_horse_with_no_nameView Answer on Stackoverflow
Solution 2 - Postgresqlconstantine-dView Answer on Stackoverflow