- 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 used to filter records based on specific conditions. You can use it to retrieve data that meets certain criteria from the database.
Key Features of Node.js MySQL Where
- Filter Records: Use
WHERE
clause to retrieve records that meet specific conditions. - Multiple Conditions: Combine conditions using
AND
orOR
for more complex filtering. - Comparison Operators: Use operators like
=
,>
,<
,BETWEEN
,LIKE
, etc. - Wildcards with LIKE: Use wildcards to perform pattern matching.
- Prepared Statements: Use placeholders (
?
) to safely insert values into the query.
Step 1 Prerequisites
Make sure MySQL is installed and the mysql2
package is added to your Node.js project.
npm install mysql2
Step 2 Basic Query with WHERE Clause
You can use the WHERE
clause to filter records based on a single condition.
Example Code
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Select records where name is 'John Doe'
const selectQuery = 'SELECT * 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('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: 'john@example.com' }
]
Step 3 Using Multiple Conditions with AND/OR
You can combine multiple conditions using AND
or OR
to create more complex filters.
Example Code with AND
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Select records where name is 'John Doe' and email is 'john@example.com'
const selectQuery = 'SELECT * FROM users WHERE name = ? AND email = ?';
const values = ['John Doe', 'john@example.com'];
connection.query(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: 'john@example.com' }
]
Example Code with OR
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Select records where name is 'John Doe' or email is 'john@example.com'
const selectQuery = 'SELECT * FROM users WHERE name = ? OR email = ?';
const values = ['John Doe', 'john@example.com'];
connection.query(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Doe', email: 'john@example.com' }
]
Step 4 Using Comparison Operators
You can use various comparison operators with the WHERE
clause to filter data, such as =
, >
, <
, >=
, <=
, <>
, BETWEEN
, etc.
Example Code with Greater Than
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Select records where age is greater than 25
const selectQuery = 'SELECT * FROM users WHERE age > ?';
const values = [25];
connection.query(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 2, name: 'Jane Doe', email: 'jane@example.com', age: 30 },
{ id: 3, name: 'Sam Smith', email: 'sam@example.com', age: 35 }
]
Step 5 Using LIKE for Pattern Matching
You can use the LIKE
operator with wildcards to filter records based on pattern matching.
Example Code with LIKE
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Select records where the name starts with 'John'
const selectQuery = 'SELECT * FROM users WHERE name LIKE ?';
const values = ['John%'];
connection.query(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'John Smith', email: 'john.smith@example.com' }
]
Step 6 Using Prepared Statements
Prepared statements allow you to safely insert user input into SQL queries, avoiding SQL injection.
Example Code with Prepared Statements
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Replace with your MySQL username
password: '', // Replace with your MySQL password
database: 'testdb' // Replace with your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err.stack);
return;
}
// Prepared statement to filter records where name is 'John Doe'
const selectQuery = 'SELECT * FROM users WHERE name = ?';
const values = ['John Doe'];
connection.execute(selectQuery, values, (err, results) => {
if (err) {
console.error('Error fetching records:', err.stack);
return;
}
console.log('Filtered records:', results);
});
// Close the connection
connection.end();
});
Output:
Filtered records: [
{ id: 1, name: 'John Doe', email: 'john@example.com' }
]
Summary
The WHERE
clause in MySQL is powerful for filtering data based on conditions. You can combine multiple conditions with AND
/OR
, use comparison operators like =
, >
, <
, and perform pattern matching with LIKE
. Prepared statements help secure your queries by avoiding SQL injection.