Auto increment in postgres/sequelize

Asked

Viewed 37 times

0

I have a Postgres database using Sequelize (Node/express) as ORM. I have a table called Students, there are columns: id and name.

In this table Students, I have several registered students, however, a detail: the last registered ID is the 34550 and the first is the 30000, are from an import from a previous database, I need to continue counting from the 34550, that is, from the last registered student. However, when registering a student via API, the generated ID is below 30000. I know that in mysql the ID field being AUTO INCREMENT would already solve, however, from what I understand, postgres works in a different way.

How could I solve this problem?

The Migration used to create the table is as follows:

    module.exports = {
    up: (queryInterface, Sequelize) => {
      return queryInterface.createTable('students', {
        id: {
          type: Sequelize.INTEGER,
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
        },
        name: {
          type: Sequelize.STRING,
          allowNull: false,
        },
      });
    },
  
    down: (queryInterface) => {
      return queryInterface.dropTable('students');
    },
  };

Table print:

inserir a descrição da imagem aqui

1 answer

1


In postgres when creating an auto-incremented field automatically a Quence is created.

When we create a new record in the id field table it takes as default value the nextval() of Quence.

To solve your problem, simply change the Current value of the Quence that currently must be under 3000 and put it as 34550.

To do this run the command:

SELECT setval('public.students_id_seq', 34550, true);

When registering a new user nextval() from Quence will be 34551.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.