To delete rows of data from your SQL table using Sequelize, you need to use the provided destroy()
method.
The destroy()
method can be called from any Model
or instance of your Model
to delete rows from your table.
For example, suppose you have a table of Cities
with the following data:
+----+------------+
| id | cityName |
+----+------------+
| 1 | York |
| 2 | Bristol |
| 3 | Manchester |
| 4 | London |
| 5 | Glasgow |
+----+------------+
To delete any row from the table above, you need to first create a Model
of that table as shown below:
const City = sequelize.define(
"City",
{ cityName: Sequelize.STRING },
{ timestamps: false }
);
After that, you can call the destroy()
method from the City
model.
The following code seeks to delete all rows where the cityName
is Manchester
:
await City.destroy({
where: { cityName: "Manchester" },
});
The destroy()
method requires the where
option to be present on the method or it will throw an error on execution.
Sequelize will generate and execute the following SQL statement to your connected database:
DELETE FROM `Cities`
WHERE `cityName` = 'Manchester'
The statement above will delete all rows that match the specified where
condition.
Now the data on the Cities
table will be as follows:
+----+----------+
| id | cityName |
+----+----------+
| 1 | York |
| 2 | Bristol |
| 4 | London |
| 5 | Glasgow |
+----+----------+
The destroy()
method can also be called from any Model
instance, whether you get that instance from creating a new row or finding it from your table.
The example below shows how to delete a row from a found instance using the findOne()
method:
const row = await City.findOne({
where: { cityName: "Glasgow" },
});
if (row) {
await row.destroy(); // deletes the row
}
And that’s how you can delete row(s) from the SQL table with Sequelize.