Monday 22 August 2016

PostgreSQL setval Sequence - PostgreSQL manually alter sequence - Reset sequence of setval in PostgreSQL - Ali Raza Bhayani


In one of the my PostgreSQL tables, I used a very handy builtin Sequence Manipulation function setval() of PostgreSQL to generate Primary Keys in a sequential and controlled manner. But during a migration, I wanted to identify new records by Primary Key sequence greater than thousand. A very handy and tested recipe to restart the setval() function sequence for such cases is by using RESTART WITH in the following way:
ALTER SEQUENCE seq RESTART WITH 1000;
is equivalent to:
    SELECT setval('sequence_name', 1, FALSE);
Either of the above statements may be used to restart the sequence and for getting the next value following statement can be used:
    nextval('sequence_name')
The above recipe can also be used to reset PostgreSQL primary key sequence when it falls out of sync.

9 comments:

  1. Replies
    1. In PostgreSQL, setval is a function used to set the current value of a sequence. This can be useful when you need to reset or initialize a sequence after manually inserting data or making adjustments. Here’s how to use it:

      Syntax
      sql
      Copy code
      SELECT setval('sequence_name', new_value, is_called);
      sequence_name: The name of the sequence you want to modify.
      new_value: The value you want the sequence to be set to.
      is_called: A boolean value that determines whether the next call to nextval should return new_value (false) or new_value + 1 (true).

      Big Data Projects For Final Year Students

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. PostgreSQL NULL value

    ReplyDelete
  4. ZModeler Crack is an ideal included 3D demonstrating an interest which intends to benefit visual specialists joined by making the low. Zmodeler 3 Crack

    ReplyDelete