Search code examples
mysqlnode.js

find number of rows in returned mysql result (nodejs)


When using felixge's mysql for node.js, how can I ask the result object for the number of returned rows? I have a rather expensive query so I don't want to run a COUNT(*) first, just to then run a query a second time.


Solution

  • If it's a select query, just take the length of the returned array.

    connection.query(sql, [var1,var2], function(err, results) {
        numRows = results.length;
    });
    

    If it's an update/delete query, the returned dictionary will have an affectedRows variable.

    connection.query(sql, [var1,var2], function(err, result) {
        numRows = result.affectedRows;
    });