Table of Contents
- Preliminary operations
- Create Database MySQL
CREATE DATABASE command is used to create a new database in MySQL.
This tutorial will show you the command syntax and several practical examples to best learn how to use it.
Create Database MySQL
In this section we will see how to create a database via command line using MySQL.
Before starting, however, I want to show you how to see which databases are already present.
Let’s jump right into the code without wasting any more time!
How to check list of databases in MySQL
To check which databases have already been created just use the
SHOW DATABASES command.
Let’s see the syntax first and then an example of output.
As you can see this command returns the list of databases that are already present.
Keep in mind that some of the ones you will see in the list are system ones, for example, in my case I just created the
In the next section we will use this command after creating a new database in order to check that it has been created correctly.
How to create a new database in MySQL
To create a new database in MySQL use the
CREATE DATABASE command.
The syntax is as follows:
CREATE DATABASE <database_name>;
Pretty simple isn’t it?
Let’s try to create a database called
CREATE DATABASE test_db;
The new database will be created by running this command. To verify, you can use the command seen in the previous section.
How to create a new database if it does not exist in MySQL
In the previous section we saw how to create a database, in particular we created the
But what happens if we try to repeat the same command?
MySQL does not allow us to create two databases with the same name, so an error is raised.
However in MySQL it is possible to slightly modify the
CREATE DATABASE command to work around this problem.
CREATE DATABASE if not exists test_db;
if not exists in fact we can run the same command several times and the database will be created only the first time.
Here we are at the end of this tutorial, as always I hope it was useful to you and that now you know how to best manage each scenario for creating new databases using MySQL.
If you are in trouble, do not hesitate to write me in the comments, otherwise take a look at the latest posts!