'how can I delete all rows in a SQLite table which contains an element from an array

I have a SQLite table (masterTable, below) in which one of the columns contains ledger numbers.

What I'm trying to do in node.js, is to delete rows from the masterTable only if the column (thisColumn, see below) matchs the elements from a given array (ledger_num, see below). if the column contains any element from the array then the entire row must be deleted

Namely, I have the following array(const ledger_num), with an unknown number of elements in it

 const ledger_num = ['g12', 'g16', 'g45', 'gXX'];
sqlite table = 
thisColumn | name | date    | age | gender
g1         | bob  | 15/1/21 | 15  | male
g2         | john | 1/2/21  | 19  | male
g3         | Emma | 9/12/21 | 20  | female
.
.
g12        | rose | 1/1/21  | 21  | female
.
.
g16        | ben  | 8/8/21  | 31  | male
.
.
g45        | toby | 6/11/21 | 31  | male
.
gXX        | ---- | ---     | --  | ----
db.run(`DELETE FROM masterTable WHERE thisColumn = ?`,ledger_num ,(err)=>{
if(err) console.log(err)
})

//so this is what i was doing but this clearly does nothing 

How do I do this in node.js so that the values from thisColumn, which match any of the elements in ledger_num, are deleted?

after deleting, the SQLite table should be  
thisColumn | name | date    | age | gender
g1         | bob  | 15/1/21 | 15  | male
g2         | john | 1/2/21  | 19  | male
g3         | Emma | 9/12/21 | 20  | female
.
.
gXX        | ---- | ---     | --  | ----


Solution 1:[1]

You can do this by updating your sql command to include a set by using the sql IN statement, then mapping over the array values replacing them with ? and passing the array in as the next argument:

db.run('DELETE FROM masterTable WHERE thisColumn IN ' +
   `(${ledger_num.map(function() { return '?' }).join(',')})`, 
   ledger_num,
   (err)=>{
      if(err) console.log(err)
   }
)

You create an array of ['?'] for every item in the ledger_num array then use the join() method to cast it to a string with , between.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1