Building SQL from multiple combinations of query parameters I have a node.js/express.js based REST application. In one GET service I am querying data based on different set of request parameters. I am looking for a better way to implement it.

function handleGet(connection,req,res) {

var sql = 'SELECT id, name, age, rent, marks FROM student WHERE class = 10';

if (req.param('minAge') &amp;&amp; req.param('maxAge')) {
    sql = sql + ' AND age BETWEEN ' + connection.escape(req.param('minAge')) + ' AND ' + connection.escape(req.param('maxAge'));
}

if (req.param('minRent') &amp;&amp; req.param('maxRent')) {
    sql =sql + ' AND rent BETWEEN ' + connection.escape(req.param('minRent')) 
        + ' AND ' + connection.escape(req.param('maxRent'));
};

if (req.param('marks')) {
    sql = sql + ' AND marks &gt;= ' + connection.escape(req.param('marks'));
};

};



var limit = ('undefined' === typeof req.params.limit) ? 20: req.params.limit;

connection.query(sql + ' ORDER BY id DESC LIMIT ' + limit, function handleSql(err, rows){
        if (err){ logAndRespond(err,res); return; }
        if (rows.length === 0){ res.send(204); return; }
        res.json(200, {'students':rows});
        connection.release();
});
}


Data can be queried by passing difference combination request parameters. Can anyone please suggest any better (reusable, abstract, robust) way of doing it? I was wondering if I can create a module for building query. Something like setting all param values in the module and let the module validate and construct the query.
Instead of dynamic string concatenation, you can do a logic trick. I'm going to use named sql placeholders for clarity. You'll obviously need to implement the code, I'm just giving you the idea.

select a
     , b
     , c
  from someTbl
 where (:PMaxAge  is null or maxAge &lt;= :PMaxAge)
   and (:PMinRent is null or rent   &gt;= :PMinRent)
   and (:PMaxRent is null or rent   &lt;= :PMaxRent)
   -- etc ...


You may need to check for an empty string instead of checking for null to detect when a param was omitted depending on you implementation, but you get the point - let each criteria be satisfied if the param is missing.