Skip to main content
Delete Your Table Data by ID using Sequelize

Delete Your Table Data by ID using Sequelize

in this Sequelize tutorial, We’ll learn how to delete table data by the ID column using Sequelize. I have already shared How To Add multiple rows using Sequelize bulkCreate() method.

Sequelize has inbuilt a Model.destroy() method that you can use to delete rows of data from your database table.

The destroy() method requires the where parameter to identify which row you want to delete from the table.

Let’s take the employee table which has the following table:

You can define Employee Models corresponding to the above table:

const Employee = sequelize.define("Employee", {
 id: {
  type: Sequelize.INTEGER,
  autoIncrement: true,
  primaryKey: true
 },
 employee_name: {
  type: Sequelize.STRING,
 },
 employee_salary: {
  type: Sequelize.INTEGER,
 },
 employee_age: {
  type: Sequelize.INTEGER,
 },
 {
  timestamps: false,
 }
});

in the above sequelize model, I have defined id column as a primary Key.

Delete Row by Id in Sequelize

You can call destroy() from the Employee model to delete a row by its id value:

const count = await Employee.destroy({ where: { id: 2 } });
console.log(deleted row(s): ${count});

The code will return 1, the number of row(s) deleted from the table.

Delete row By Column name

The example below shows how to delete a row from a found instance using the findOne() method:

const row = await City.findOne({
  where: { employee_name: "Tiger Nixon" },
});

if (row) {
  await row.destroy(); // deletes the row
}

And that’s how you can delete row(s) from the SQL table with Sequelize.

Leave a Reply

Your email address will not be published. Required fields are marked *