๐Ÿงพ Node.js โ€“ MySQL WHERE โ€“ Filter Records with SQL Conditions in Node.js


๐Ÿงฒ Introduction โ€“ Why Use the WHERE Clause in Node.js?

The WHERE clause is used in SQL to filter records based on specific conditions, ensuring you only retrieve the rows you need. With Node.js and the mysql module, you can easily combine the power of SQL and JavaScript to build dynamic, secure, and efficient data queries.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to apply WHERE clauses in Node.js MySQL queries
  • Use parameterized queries for security
  • Combine AND, OR, LIKE, and range filters
  • Handle user input safely in filtered queries

โš™๏ธ Setup โ€“ MySQL Connection File (db.js)

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'testdb'
});

db.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL');
});

module.exports = db;

๐Ÿ” SELECT with WHERE Clause

โœ… Basic Example: Get User by ID

const db = require('./db');
const userId = 2;

db.query('SELECT * FROM users WHERE id = ?', [userId], (err, result) => {
  if (err) throw err;
  console.log('User:', result);
});

๐Ÿงช Output:

[ { id: 2, name: 'Bob', email: 'bob@example.com' } ]

โœ… Use WHERE with Multiple Conditions (AND)

db.query(
  'SELECT * FROM users WHERE name = ? AND email = ?',
  ['Alice', 'alice@example.com'],
  (err, result) => {
    if (err) throw err;
    console.log('User found:', result);
  }
);

โœ… Use OR in WHERE Clause

db.query(
  'SELECT * FROM users WHERE name = ? OR email = ?',
  ['Alice', 'bob@example.com'],
  (err, result) => {
    if (err) throw err;
    console.log('Matched Users:', result);
  }
);

๐Ÿ”Ž Filter Using LIKE Operator

db.query(
  "SELECT * FROM users WHERE name LIKE ?",
  ['A%'],
  (err, result) => {
    if (err) throw err;
    console.log('Users starting with A:', result);
  }
);

๐Ÿง  % is a wildcard. 'A%' means names starting with “A”.


๐Ÿ“† Filter by Range (BETWEEN, >, <)

db.query(
  "SELECT * FROM users WHERE id BETWEEN ? AND ?",
  [1, 5],
  (err, result) => {
    if (err) throw err;
    console.log('Users in range:', result);
  }
);

๐Ÿงฑ Best Practices for WHERE Queries in Node.js

โœ… Practice๐Ÿ’ก Why Itโ€™s Important
Use ? placeholdersPrevents SQL injection
Always validate user inputAvoids runtime errors or logic bugs
Select only necessary fieldsReduces payload size and improves performance
Check if results are emptyEnsures you handle no-result cases gracefully
Combine conditions logicallyUse AND, OR, and parentheses effectively

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

The WHERE clause in Node.js + MySQL is a powerful filter tool that lets you query only what you need, enhancing security, performance, and user experience.

๐Ÿ” Key Takeaways:

  • Use WHERE to narrow down query results
  • Use ? for dynamic user-safe filtering
  • Combine filters with AND, OR, LIKE, BETWEEN, etc.
  • Always check query result length before processing

โš™๏ธ Real-world relevance:
Used in login systems, search filters, admin dashboards, reporting engines, and audit logs.


โ“FAQs โ€“ Using WHERE Clause in MySQL with Node.js


โ“ Can I combine multiple WHERE conditions in Node.js?
โœ… Yes. Use AND, OR, LIKE, or IN with placeholders:

'SELECT * FROM users WHERE name = ? AND email = ?'

โ“ How do I handle cases when no results are returned?
โœ… Check if the result is an empty array:

if (result.length === 0) console.log('No records found');

โ“ How to filter using wildcards in Node.js MySQL?
โœ… Use LIKE with % and pass it via placeholders:

'SELECT * FROM users WHERE name LIKE ?', ['%son%']

โ“ Can I filter by date ranges with WHERE?
โœ… Yes. Use:

SELECT * FROM logs WHERE created_at BETWEEN '2024-01-01' AND '2024-01-31'

โ“ Are WHERE conditions case-sensitive in MySQL?
โœ… By default, string matches are not case-sensitive in MySQL (unless the collation is case-sensitive).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงพ Node.js โ€“ MySQL Where

Or Copy Link

CONTENTS
Scroll to Top