- 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 Delete
The DELETE
statement in MySQL is used to delete existing records from a table. It allows you to remove one or more rows from the database based on a condition.
Key Features of Node.js MySQL Delete
- Delete Specific Rows: You can delete specific rows based on a condition.
- Delete All Rows: You can delete all rows in a table using the
DELETE
statement without specifying a condition. - Safe Deletion: Always use a
WHERE
clause to prevent deleting all rows by accident. - Transactional Deletion: Deleting data is often wrapped in transactions to ensure data integrity.
Step 1 Prerequisites
Ensure that MySQL is installed and the mysql2
package is added to your Node.js project.
npm install mysql2
Step 2 Basic Query to Delete Data
The simplest form of the DELETE
statement is without a condition, which removes all rows from the table.
Example Code for Deleting Specific Rows
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;
}
// Delete record from the users table where the name is 'John Doe'
const deleteQuery = 'DELETE FROM users WHERE name = "John Doe"';
connection.query(deleteQuery, (err, results) => {
if (err) {
console.error('Error deleting record:', err.stack);
return;
}
console.log('Record deleted:', results.affectedRows);
});
// Close the connection
connection.end();
});
Output:
Record deleted: 1
The result indicates that one row was deleted from the users
table where the name
column matched 'John Doe'.
Step 3 Delete All Rows from a Table
If you want to delete all rows from a table, you can omit the WHERE
clause.
Example Code for Deleting All Rows
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;
}
// Delete all records from the users table
const deleteQuery = 'DELETE FROM users';
connection.query(deleteQuery, (err, results) => {
if (err) {
console.error('Error deleting records:', err.stack);
return;
}
console.log('All records deleted:', results.affectedRows);
});
// Close the connection
connection.end();
});
Output:
All records deleted: 5
This shows that all five rows in the users
table have been deleted.
Step 4 Deleting with Multiple Conditions
You can delete rows based on multiple conditions by combining them using AND
or OR
.
Example Code for Deleting Rows with Multiple Conditions
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;
}
// Delete record from the users table where name is 'John Doe' and age is 25
const deleteQuery = 'DELETE FROM users WHERE name = "John Doe" AND age = 25';
connection.query(deleteQuery, (err, results) => {
if (err) {
console.error('Error deleting record:', err.stack);
return;
}
console.log('Record deleted with multiple conditions:', results.affectedRows);
});
// Close the connection
connection.end();
});
Output:
Record deleted with multiple conditions: 1
Step 5 Deleting Records with Limit
To delete a limited number of rows, you can use the LIMIT
clause along with DELETE
.
Example Code for Deleting Limited Rows
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;
}
// Delete only 2 records where age is 30
const deleteQuery = 'DELETE FROM users WHERE age = 30 LIMIT 2';
connection.query(deleteQuery, (err, results) => {
if (err) {
console.error('Error deleting record:', err.stack);
return;
}
console.log('Limited records deleted:', results.affectedRows);
});
// Close the connection
connection.end();
});
Output:
Limited records deleted: 2
Step 6 Using Transactions for Deletion
To ensure that the deletion process is safe and reliable, it is a good practice to use transactions.
Example Code with Transaction
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;
}
// Start a transaction
connection.beginTransaction((err) => {
if (err) {
console.error('Error starting transaction:', err.stack);
return;
}
// Delete record from users table
const deleteQuery = 'DELETE FROM users WHERE name = "Sam Smith"';
connection.query(deleteQuery, (err, results) => {
if (err) {
// Rollback transaction if an error occurs
connection.rollback(() => {
console.error('Error deleting record, transaction rolled back:', err.stack);
});
return;
}
// Commit the transaction
connection.commit((err) => {
if (err) {
console.error('Error committing transaction:', err.stack);
} else {
console.log('Transaction committed, record deleted');
}
});
});
});
// Close the connection
connection.end();
});
Output:
Transaction committed, record deleted
Summary
The DELETE
statement in MySQL allows you to remove one or more rows from a table based on specific conditions. It can be used with WHERE
, LIMIT
, and ORDER BY
to manage which rows get deleted. For safety, always use a WHERE
clause to avoid deleting all records, and consider using transactions for atomicity when performing deletions in critical applications.