MySQL - CREATE DATABASE Statement



CREATE DATABASE Statement

After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own.

You would need special privileges to create or to delete a MySQL database. So, if you have access to the root user, you can create any database using the MySQL CREATE DATABASE statement.

Syntax

Following is the syntax of the CREATE DATABASE statement −

CREATE DATABASE database_name

Where, database_name is the name of the database you need to create.

Example

Following query creates a database with name myDatabase −

CREATE DATABASE myDatabase;

Make sure you have the admin privilege before creating any database. Once a database is created, you can check it in the list of databases as follows −

show databases;

Output

The above query produces the following output −

Database
information_schema
mydatabase
performance_schema
world

The IF NOT EXISTS clause

If you try to create a database with an existing name as −

CREATE DATABASE myDatabase;

An error will be generated as −

ERROR 2006 (HY000): MySQL server has gone away MySQL CREATE 
DATABASE Statement
No connection. Trying to reconnect...
Connection id: 10
Current database: sampledb
ERROR 1007 (HY000): Can't create database 'mydatabase';

If you use the IF NOT EXISTS clause along with the CREATE statement as shown below a new database will be created and if a database with the given name, already exists the query will be ignored.

CREATE DATABASE IF NOT EXISTS myDatabase
Advertisements