Course
Create Database
MySQL Tutorial
This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.
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
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 StatementNo connection. Trying to reconnect...Connection id: 10Current database: sampledbERROR 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