SQL Create Database

Table of Contents

Introduction

The CREATE DATABASE command is used to create a new database in SQL.
This tutorial will show you the command syntax and several practical examples to best learn how to use it.

Preliminary operations

First of all, for this tutorial I assume that you have MySQL installed on your computer.
If not, you can download it and follow the instructions to install it.

Create Database SQL

In this section we will see how to create a database via command line using SQL.
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 SQL

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.

 SHOW DATABASES;

Output

SHOW DATABASES output
SHOW DATABASES 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 devinsimplewords database.

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 SQL

To create a new database in SQL 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 test_db.

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.

CREATE DATABASE output
CREATE DATABASE output

How to create a new database if it does not exist in SQL

In the previous section we saw how to create a database, in particular we created the test_db database.
But what happens if we try to repeat the same command?
SQL does not allow us to create two databases with the same name, so an error is raised.

However in SQL it is possible to slightly modify the CREATE DATABASE command to work around this problem.

CREATE DATABASE if not exists test_db;

By adding if not exists in fact we can run the same command several times and the database will be created only the first time.

Conclusion

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 SQL.
If you are in trouble, do not hesitate to write me in the comments, otherwise take a look at the latest posts!

Leave a Comment

Your email address will not be published. Required fields are marked *