Node.js MySQL WHERE clause for filtering table rows

Node.js MySQL WHERE is used to filter the selection of MySQL SELECT FROM statement records based on a condition applied to one or more columns of the TABLE.

In this tutorial, we will learn how to filter the rows of a Query selection using WHERE clause, with the help of examples.

The examples use the callback-based mysql package for Node.js. In a real application, values used in the WHERE clause should be escaped or passed through placeholders so that user input is not joined directly into the SQL string.

We shall learn to filter records of a table using following Node.js examples

Node.js MySQL WHERE syntax with SELECT query

The WHERE clause is written after the table name in a SELECT query. It may compare a column with a number, string, date, or another expression.

</>
Copy
SELECT column1, column2
FROM table_name
WHERE condition;

When the condition value comes from a JavaScript variable, prefer a placeholder query. The ? placeholder is replaced safely by the value supplied in the array.

</>
Copy
con.query(
  "SELECT * FROM students WHERE marks > ?",
  [90],
  function (err, result) {
    if (err) throw err;
    console.log(result);
  }
);

Sample MySQL students table used for Node.js WHERE examples

We shall use the following MySQL Table, in the examples of this section [DATABASE : studentsDB, Table: students]

mysql> select * from students;
+---------------+--------+-------+
| name          | rollno | marks |
+---------------+--------+-------+
| John          |      1 |    74 |
| Arjun         |      2 |    74 |
| Prasanth      |      3 |    77 |
| Adarsh        |      4 |    78 |
| Raja          |      5 |    94 |
| Sai           |      6 |    84 |
| Ross          |      7 |    54 |
| Monica Gellar |      8 |    86 |
| Lee           |      9 |    98 |
| Bruce Wane    |     10 |    92 |
| Sukumar       |     11 |    99 |
+---------------+--------+-------+
11 rows in set (0.00 sec)

If the mysql package is not already installed in your Node.js project, install it before running the examples.

</>
Copy
npm install mysql

Example 1 – Node.js MySQL WHERE with filter applied on a column

We shall apply a filter based on marks and fetch only those records with marks greater than 90.

selectFromWhere.js

</>
Copy
// include mysql module
var mysql = require('mysql');

// create a connection variable with the required details
var con = mysql.createConnection({
  host: "localhost",	// ip address of server running mysql
  user: "arjun",	// user name to your mysql database
  password: "password",	// corresponding password
  database: "studentsDB" // use the specified database
});

// make to connection to the database.
con.connect(function(err) {
  if (err) throw err;
  // if connection is successful
  con.query("SELECT * FROM students where marks>90", function (err, result, fields) {
	// if any error while executing above query, throw error
    if (err) throw err;
	// if there is no error, you have the result
    console.log(result);
  });
});

Open a terminal from the location of above .js file and run selectFromWhere.js Node.js MySQL example program.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node selectFromWhere.js 
[ RowDataPacket { name: 'Raja', rollno: 5, marks: 94 },
  RowDataPacket { name: 'Lee', rollno: 9, marks: 98 },
  RowDataPacket { name: 'Bruce Wane', rollno: 10, marks: 92 },
  RowDataPacket { name: 'Sukumar', rollno: 11, marks: 99 } ]

The query returns only the rows where marks is greater than 90. Rows with marks less than or equal to 90 are not included in the result array.

Example 2 – Node.js MySQL WHERE to use Escaping Query Values

Records may contain data with escaping values like space characters. Following Node.js MySQL example program helps you to filter records based on values containing escaping characters.

WhereEscapingValues.js

</>
Copy
// include mysql module
var mysql = require('mysql');

// create a connection variable with the required details
var con = mysql.createConnection({
  host: "localhost",	// ip address of server running mysql
  user: "arjun",	// user name to your mysql database
  password: "password",	// corresponding password
  database: "studentsDB" // use the specified database
});

// make to connection to the database.
con.connect(function(err) {
  if (err) throw err;
  // if connection is successful
  var name = "Bruce Wane";
  var query = "SELECT * FROM students where name=" + mysql.escape(name);
  con.query(query, function (err, result, fields) {
	// if any error while executing above query, throw error
    if (err) throw err;
	// if there is no error, you have the result
    console.log(result);
  });
});

Open a terminal from the location of above .js file and run WhereEscapingValues.js Node.js MySQL example program.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node WhereEscapingValues.js 
[ RowDataPacket { name: 'Bruce Wane', rollno: 10, marks: 92 } ]

mysql.escape() converts the JavaScript value into a safe SQL literal. This is useful when a string contains spaces, quotes, or other special characters. For most Node.js MySQL queries, placeholders are easier to read because the SQL statement and values remain separate.

Node.js MySQL WHERE with placeholder values

The following example performs the same name filter using a ? placeholder. The value studentName is passed as the first item in the values array.

</>
Copy
var mysql = require("mysql");

var con = mysql.createConnection({
  host: "localhost",
  user: "arjun",
  password: "password",
  database: "studentsDB"
});

con.connect(function (err) {
  if (err) throw err;

  var studentName = "Bruce Wane";

  con.query(
    "SELECT * FROM students WHERE name = ?",
    [studentName],
    function (err, result) {
      if (err) throw err;
      console.log(result);
      con.end();
    }
  );
});

Example 3 – Node.js MySQL WHERE with filter applied on two columns

We shall apply a filter based on marks and fetch only those records with marks greater than 90 and rollno less than 8.

selectFromWhere2.js

</>
Copy
// include mysql module
var mysql = require('mysql');

// create a connection variable with the required details
var con = mysql.createConnection({
  host: "localhost",	// ip address of server running mysql
  user: "arjun",	// user name to your mysql database
  password: "password",	// corresponding password
  database: "studentsDB" // use the specified database
});

// make to connection to the database.
con.connect(function(err) {
  if (err) throw err;
  // if connection is successful
  con.query("SELECT * FROM students where marks>90 && rollno<8", function (err, result, fields) {
	// if any error while executing above query, throw error
    if (err) throw err;
	// if there is no error, you have the result
    console.log(result);
  });
});

Open a terminal from the location of above .js file and run selectFromWhere.js Node.js MySQL example program.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node selectFromWhere2.js 
[ RowDataPacket { name: 'Raja', rollno: 5, marks: 94 } ]

MySQL supports && as a logical AND operator, but AND is clearer in SQL examples. With placeholders, the same two-column filter can be written as follows.

</>
Copy
var minMarks = 90;
var maxRollNo = 8;

con.query(
  "SELECT * FROM students WHERE marks > ? AND rollno < ?",
  [minMarks, maxRollNo],
  function (err, result) {
    if (err) throw err;
    console.log(result);
  }
);

Node.js MySQL WHERE with OR and LIKE conditions

Use OR when a row may match any one condition. Use LIKE when you want to search text with a pattern.

</>
Copy
con.query(
  "SELECT * FROM students WHERE marks > ? OR rollno = ?",
  [95, 1],
  function (err, result) {
    if (err) throw err;
    console.log(result);
  }
);
</>
Copy
var searchText = "R%";

con.query(
  "SELECT * FROM students WHERE name LIKE ?",
  [searchText],
  function (err, result) {
    if (err) throw err;
    console.log(result);
  }
);

Common LIKE patterns are 'R%' for names starting with R, '%ar%' for names containing ar, and '%n' for names ending with n. When mixing AND and OR, use parentheses so the condition is evaluated as intended.

Common mistakes in Node.js MySQL WHERE queries

  • Concatenating user input directly: Avoid building SQL strings with raw request values. Use placeholders or escaping.
  • Forgetting quotes around string values: Text values need proper SQL quoting. Placeholders handle this automatically.
  • Mixing AND and OR without parentheses: Add parentheses when a condition has multiple logical parts.
  • Expecting exactly one row every time: A WHERE condition can return zero, one, or many rows.
  • Not closing the connection: Use con.end() after a simple query or use a connection pool in a larger app.

Node.js MySQL WHERE FAQ

How do I use WHERE in Node.js MySQL?

Pass a SELECT query with a WHERE clause to con.query(). For example, use SELECT * FROM students WHERE marks > ? and pass the value in an array, such as [90].

Should I use mysql.escape() or placeholders in Node.js MySQL WHERE queries?

Both can be used to avoid unsafe SQL string construction, but placeholders are usually easier to read and maintain. A placeholder query keeps the SQL statement and input values separate.

How do I filter rows by two columns in Node.js MySQL?

Use AND when both conditions must be true, such as WHERE marks > ? AND rollno < ?. Use OR when any one condition may be true.

How do I search text with WHERE in Node.js MySQL?

Use the SQL LIKE operator with a placeholder. For example, WHERE name LIKE ? with the value ['R%'] searches names that start with R.

Editorial QA checklist for Node.js MySQL WHERE tutorial

  • Confirm that new Node.js MySQL examples use placeholders or clearly explain escaping.
  • Check that numeric filters, text filters, AND, OR, and LIKE conditions are covered.
  • Verify that the old examples remain unchanged while the safer placeholder pattern is clearly recommended.
  • Ensure new command-line examples use language-bash and new syntax-only examples use syntax.
  • Keep the conclusion linked to the existing Node.js Tutorial and Node.js MySQL pages.

Conclusion

In this Node.js TutorialNode.js MySQL Module Section – Node.js MySQL WHERE – We have learned to filter the selection of MySQL SELECT FROM statement records based on a condition applied to one or more columns of the MySQL Table.