How can you avoid getting an error if you are deleting a table which does not exist using Python?

PythonServer Side ProgrammingProgramming

There might be a scenario where you might be deleting a table which actually does not exist in your database. It is possible that while executing the command to delete a table from the database,we may give wrong name of the table which doesnot exist in our database. The another possibility is that you are deleting a table which was already deleted by someone else who has access to the database. In this scenario you will get an error while executing the command since the table you wish to delete is not present.

This error can be avoided by checking if the table is present and then deleting it. If the table is not present, your command to delete that table will not be executed without giving any error.

The IF EXISTS statement is used to verify if the table we wish to delete is present ornot.



The above statement performs the drop table operation only if the table exists, else it does not perform any action and hence, prevents the occurrence of error.

Steps to delete a table after checking if it exists in database using MySQL in python

  • import MySQL connector

  • establish connection with the connector using connect()

  • create the cursor object using cursor() method

  • create a query using the appropriate mysql statements

  • execute the SQL query using execute() method

  • close the connection


Suppose, we need to delete a table from our database, but before that we need to check if it exists or not.

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your


query="DROP TABLE IF EXISTS Employees "
print("TABLE DROPED..")


The above code deletes the table ”Employees” from the database if it exists. Else, if the table doesnot exist,it does not give any error.


Updated on 10-Jun-2021 12:46:49