Search code examples
node.jsknex.jsbatch-delete

How to batch delete in Knex?


I'd like to perform batch deletion using knex.js. We have batchInsert as an API method , but nothing as far as batchDelete is concerned.

I tried async iteration and delete each row separately. But it's not efficient ,because we have lot of server to DB calls. I'm looking into a possibility, if DB have 100 records the batch of 25 records should be delete every time

Any ideas welcome!!


Solution

  • Given ids of the items that you need to delete, you can use the In SQL statement.

    It should look like:

    Delete from tableName Where id In (1,2,3,45,636,52);
    

    In order to build this query using knex

    db('tableName')
      .delete()
      .whereIn('id', [1, 2, 3, 45, 636, 52]);