- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MySQL Where
In Node.js, when working with MySQL, the WHERE clause is the primary tool used to filter records. Without it, a SELECT statement would return every single row in a table, which is rarely what you want in a production application. By using WHERE, you can pinpoint specific data—such as finding a user by their ID, fetching orders placed within the last 24 hours, or searching for products within a certain price range.
WHERE clause as a filter for your database. It evaluates every row against your criteria and only returns the ones that evaluate to "True."
Key Features of Node.js MySQL Where
- Precise Filtering: Narrow down results to only the data you actually need, reducing memory usage in your Node.js app.
- Logical Logic (AND/OR): Chain multiple requirements together to create sophisticated search queries.
- Flexible Comparisons: Go beyond simple equality with operators like "greater than" (
>), "less than" (<), and "not equal" (!=). - Pattern Matching: Find partial matches (like searching for a username) using the
LIKEoperator and wildcards. - Security via Placeholders: Protect your database from malicious attacks by using
?placeholders (Prepared Statements) instead of concatenating strings.
Step 1 Prerequisites
Before querying your database, ensure you have the mysql2 driver installed. While the original mysql package exists, mysql2 is faster and offers better support for modern JavaScript features.
npm install mysql2
Step 2 Basic Query with WHERE Clause
The simplest way to use WHERE is to match a column against a single value. In the example below, we look for a specific user. Notice the use of the ? symbol; this is a placeholder that the library will safely swap with our variable.
?) for variables. This automatically sanitizes your input, preventing SQL Injection attacks.
Example Code
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'testdb'
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Find a user named 'John Doe'
const selectQuery = 'SELECT id, name, email FROM users WHERE name = ?';
const values = ['John Doe'];
connection.query(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('User found:', results);
});
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: '[email protected]' }
]
Step 3 Using Multiple Conditions with AND/OR
In real-world apps, you often need to check multiple things at once. For example, a login system needs to check if the username AND the password are correct. Conversely, you might want to find users who live in New York OR London.
Example Code with AND
The AND operator requires all conditions to be met.
// Select records where both name and email match exactly
const selectQuery = 'SELECT * FROM users WHERE name = ? AND email = ?';
const values = ['John Doe', '[email protected]'];
connection.query(selectQuery, values, (err, results) => {
if (err) throw err;
console.log('Matched both criteria:', results);
});
Example Code with OR
The OR operator returns a result if any of the conditions are met.
// Select records where either the name matches OR the email matches
const selectQuery = 'SELECT * FROM users WHERE name = ? OR email = ?';
const values = ['John Doe', '[email protected]'];
connection.query(selectQuery, values, (err, results) => {
if (err) throw err;
console.log('Matched at least one criteria:', results);
});
AND and OR in a single query, use parentheses to group your logic, e.g., WHERE status = 'active' AND (role = 'admin' OR role = 'editor').
Step 4 Using Comparison Operators
Filtering isn't limited to "equals." You can use standard mathematical operators to filter numerical data, dates, or even alphabetical ranges.
>and<: Greater than / Less than.>=and<=: Greater than or equal / Less than or equal.<>or!=: Not equal to.BETWEEN: Useful for ranges (e.g., prices between 10 and 50).
Example Code with Greater Than
// Fetching users over a certain age (e.g., for age-restricted content)
const minAge = 25;
const selectQuery = 'SELECT name, age FROM users WHERE age > ?';
connection.query(selectQuery, [minAge], (err, results) => {
if (err) throw err;
console.log('Users older than 25:', results);
});
NULL requires special syntax. You cannot use WHERE email = NULL; you must use WHERE email IS NULL or WHERE email IS NOT NULL.
Step 5 Using LIKE for Pattern Matching
The LIKE operator is used when you don't know the exact value. It uses two main wildcards:
%: Represents zero, one, or multiple characters._: Represents a single character.
Example Code with LIKE
// Search for any user whose name starts with "John"
// 'John%' will match 'John', 'John Doe', and 'Johnny'
const searchQuery = 'John%';
const selectQuery = 'SELECT * FROM users WHERE name LIKE ?';
connection.query(selectQuery, [searchQuery], (err, results) => {
if (err) throw err;
console.log('Search Results:', results);
});
'%John'). These prevent MySQL from using indexes, which can significantly slow down your query on large tables.
Step 6 Using Prepared Statements
While connection.query() is common, the mysql2 library provides a more robust connection.execute() method for prepared statements. This is slightly more efficient if you run the same query multiple times with different values, as the database "pre-compiles" the SQL logic.
Example Code with Prepared Statements
const mysql = require('mysql2');
const connection = mysql.createConnection({ host: 'localhost', user: 'root', database: 'testdb' });
// connection.execute is the preferred way for prepared statements
const selectQuery = 'SELECT * FROM users WHERE id = ?';
const userId = 1;
connection.execute(selectQuery, [userId], (err, results) => {
if (err) {
console.error(err);
return;
}
console.log('User found via prepared statement:', results);
});
'${variable}' inside your query string. Even if you think the data is safe, always use placeholders to ensure your application remains secure as it scales.
Summary
Mastering the WHERE clause is essential for any Node.js developer working with databases. By combining comparison operators, logical AND/OR conditions, and LIKE patterns, you can build complex data-driven features. Always prioritize security by using prepared statements and placeholders to keep your user data safe from injection attacks.