Skip to content
Related Articles

Related Articles

NodeJs MySQL Drop Table
  • Difficulty Level : Medium
  • Last Updated : 08 Feb, 2021

DROP TABLE Query is used to Delete or Drop a table from MySQL Database.

Syntax:

  • This will delete users table. But this will throw error if users table is not there.
    DROP TABLE users
  • This will delete users table only if it exist.
    DROP TABLE IF EXISTS users

      Modules:

      • mysql: To handle MySQL connection and Queries
        npm install mysql

      SQL gfg_db
      Database Preview (showing tables):



      Example 1: Delete users Table

      Javascript




      const mysql = require("mysql");
        
      let db_con  = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: '',
          database: 'gfg_db'
      });
        
      db_con.connect((err) => {
          if (err) {
            console.log("Database Connection Failed !!!", err);
            return;
          }
        
          console.log("We are connected to gfg_db database");
        
          // here is our query
          let query = 'DROP TABLE users';
        
          db_con.query(query, (err, rows) => {
              if(err) throw err;
        
              console.log('Deleted users Table');
          });
      });

      Output:

      Example 2: Delete users Table only if it Exists

      Javascript




      const mysql = require("mysql");
        
      let db_con  = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: '',
          database: 'gfg_db'
      });
        
      db_con.connect((err) => {
          if (err) {
            console.log("Database Connection Failed !!!", err);
            return;
          }
        
          console.log("We are connected to gfg_db database");
        
          // notice the if exists in below query
          let query = 'DROP TABLE IF EXISTS users';
        
          db_con.query(query, (err, rows) => {
              if(err) throw err;
        
              console.log('Deleted users Table');
          });
      });

      Output:

      My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :