Mysql Delete in NodeJs
Deleting records from a MySQL table in Node.js is straightforward using either mysql or mysql2. Below are examples using both libraries.
✅ Step 1: Install MySQL Package
npm install mysql
Or for async/await:
npm install mysql2
🗑️ Step 2: Delete Data From a Table
🔧 Using mysql (Callback-style):
const mysql = require('mysql2/promise');async function deleteUser() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); // Delete user with id = 1 const [result] = await connection.execute('DELETE FROM users WHERE id = ?', [1]); console.log(`Deleted ${result.affectedRows} row(s)`); await connection.end();}deleteUser();
🧠 Additional Delete Options
| Task | SQL Query |
|---|---|
| Delete by name | DELETE FROM users WHERE name = 'John' |
| Delete all records | DELETE FROM users |
| Delete with condition | DELETE FROM users WHERE age < 18 |
| Delete with LIMIT | DELETE FROM users LIMIT 5 |
🔥 Be careful with
DELETE FROM users— it wipes the whole table.