
Mysql Drop Table in NodeJs
Dropping a MySQL table in Node.js is simple and quick using either mysql
or mysql2
.
Let’s go through how to do it step by step 👇
✅ Step 1: Install the MySQL Package
npm install mysql
Or for async/await:
npm install mysql2
🧨 Step 2: Drop Table in MySQL
🔧 Using mysql
(Callback style):
const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL!'); const sql = 'DROP TABLE IF EXISTS users'; // Drop only if it exists connection.query(sql, (err, result) => { if (err) throw err; console.log('Table dropped!'); connection.end(); });});
🔧 Using mysql2
(Async/Await):
const mysql = require('mysql2/promise');async function dropTable() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const sql = 'DROP TABLE IF EXISTS users'; await connection.query(sql); console.log('Table dropped!'); await connection.end();}dropTable();
🧠 Notes:
DROP TABLE
permanently deletes the table and all its data.Use
IF EXISTS
to prevent errors if the table doesn’t exist.Be extra careful — once dropped, the data is gone unless you’ve backed it up.
Want to:
Drop multiple tables?
Recreate the table after dropping?
Check if a table exists before running the command?