Check if database exists in MYSQL


Some times we need to create database while at run time, Suppose if the specified database exists already, it will show error, in order to avoid those kind of error we need to check whether the specified database exists already

Some times we need to create database while at run time, Suppose if the specified database exists already, it will show error, in order to avoid those kind of error we need to check whether the specified database exists already.

The following query is used to check whether the database specified to create already exists in the database.




SELECT SCHEMA_NAME as DB FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "test";



When we execute the above query by replace the "test" with actual database, i ll show the database in case if it exists other wise it will display empty set of records.

or else we can make use of the following query to display the result even when the database does not exists



SELECT IF( EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'test') , 'Exists','Not Exists') as DB;





We can also proceed creating database using the following query



CREATE DATABASE IF NOT EXISTS 'test';



but it will ignore the checking process.


Comments

Author: Pawan Awasthi24 Jul 2011 Member Level: Gold   Points : 1

Hi Priya,

Good article as this is the common issue which we face frequently while connecting ot he database but we try to resolve this issue by doing lot much R&D.
So its better to first check for the database existance and then go for rest of the tranactions.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: