I want to build a SQL query such that the filter clauses can be added dynamically with placeholder.
Ex :
router.get('/test',(req,res) => {
const {name , account , id} = req.query
const nameFilter = name === '' ? ':nameVal' : `and username = :nameVal`
const accountFilter = account === '' ? ':accountVal' : `and accountnumber = :accountVal`
const result = connection.execute(' SELECT * FROM WHERE ID = :idVal ' + nameFilter + accountFilter),
{
nameVal : name,
accountVal : account,
idVal : id
},
}
res.send(result.rows)
)
Now the issue is, when the query parameter has data, the filters are working perfectly, but when passing an empty string, I get a SQL error
illegal variable name/number
What could be the best solution to design the query with such requirements?
When query parameters are passed with value or no value the filter could work dynamically, having placeholder in the query.