Node.js MySQL Drop Table

🚀 Node.js MySQL – DROP TABLE

The DROP TABLE statement is used to completely remove a table from the database, including all its data.


1. Install mysql2

npm install mysql2

2. Connect to MySQL Database

const mysql = require("mysql2");

const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});


3. Drop a Table

const sql = "DROP TABLE users";

connection.query(sql, (err, result) => {
if (err) throw err;
console.log("Table 'users' dropped successfully!");
});


4. Drop Table Only If Exists

Prevents errors if the table does not exist:

const sql = "DROP TABLE IF EXISTS users";

connection.query(sql, (err, result) => {
if (err) throw err;
console.log("Table 'users' checked/dropped successfully!");
});


5. Using Async/Await

const mysql = require("mysql2/promise");

async function dropTable() {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});

const sql = "DROP TABLE IF EXISTS users";
await connection.execute(sql);
console.log("Table 'users' dropped successfully!");

await connection.end();
}

dropTable();


⚠️ Important Notes

  • DROP TABLE is irreversible — all data will be lost.

  • Use IF EXISTS to avoid errors when running scripts multiple times.

  • Always make database backups before dropping tables in production.

You may also like...