Search code examples
postgresqlsequelize.js

Auto increment in postgres/sequelize


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

In this students table, I have several registered students, but a detail: the last registered ID is 34550 and the first is 30000, they come from an import from a previous database, I need to continue counting from 34550, or that is, from the last registered student. However, when I register a student via API, the generated ID is below 30000. I know that in mysql the ID field being AUTO INCREMENT would solve it, however, as I understand it, 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:

enter image description here


Solution

  • Based on Frank comment, I was able to adjust using:

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