Sling Academy
Home/Node.js/SequelizeJS: How to reset auto-increment ID after deleting records

SequelizeJS: How to reset auto-increment ID after deleting records

Last updated: February 19, 2024

Overview

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more. This tutorial will guide you through resetting the auto-increment value of a table’s ID after records have been deleted, using Sequelize.

Before delving into resetting the auto-increment value, it’s important to understand what it is and why it might be necessary. An auto-increment ID automatically increments with each new record inserted into the table, usually serving as the primary key. After deleting records from a table, especially in a development or testing environment, you might want to reset this ID for consistency or to avoid reaching the maximum limit of the ID data type.

Let’s begin with the basics.

Checking Current Auto-Increment Value

First, let’s see how to check the current auto-increment value for a table. Although this process doesn’t directly involve Sequelize, it sets the stage for understanding the initial state of your database.

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = 'your_table_name' AND table_schema = DATABASE();

This SQL statement will show you the current auto-increment value for the specified table in your schema.

Deleting Records

Deleting records in Sequelize is straightforward. Here’s a basic example:

const { User } = require('./models');

async function deleteUsers() {
  await User.destroy({
    where: {},
    truncate: true
  });
}

deleteUsers();

This code will delete all records from the User table. The truncate option not only deletes the records but also resets the auto-increment ID in some databases, such as MySQL and PostgreSQL. However, for databases that don’t support this through truncate, we need a different approach.

Manually Resetting the Auto-Increment ID

Now, let’s get into how to manually reset the auto-increment value after deleting records. The method varies per database, but I’ll show you a generic approach.

await sequelize.query('ALTER TABLE tableName AUTO_INCREMENT = 1');

This Sequelize command explicitly sets the auto-increment value of tableName to 1, or any other number you prefer. It’s important to execute this command judiciously, considering the current state of your database to avoid ID conflicts.

Advanced Example: Resetting in a Transaction

Transactions ensure that operations are executed in a safe manner, maintaining data integrity. Here’s how you can reset the auto-increment ID within a transaction:

const { sequelize } = require('./models');

async function resetAutoIncrement() {
  await sequelize.transaction(async (t) => {
    await sequelize.query('DELETE FROM tableName', { transaction: t });
    await sequelize.query('ALTER TABLE tableName AUTO_INCREMENT = 1', { transaction: t });
  });
}

resetAutoIncrement();

This wraps the deletion and auto-increment reset commands in a transaction, ensuring that either both commands succeed or neither does. This approach is particularly useful in scenarios where maintaining data consistency is crucial.

Conclusion

Resetting the auto-increment value after deleting records in Sequelize involves understanding the specifics of your database system. Although Sequelize abstracts many complexities of database interactions, certain operations like resetting the auto-increment value require direct SQL commands. This tutorial has guided you through different methods of resetting the auto-increment ID, ensuring that you can maintain the consistency and integrity of your database.

Next Article: Working with Paranoid Tables in Sequelize

Previous Article: A Deep Dive into Sequelize’s Timestamps

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates
  • ExpressJS: How to pass variables to Pug templates