SQL Create Database Statement
In this lesson, you will learn how to create a database using SQL.
Create database in SQL
The CREATE DATABASE
statement is used to create a new SQL database.
Syntax
CREATE DATABASE database_name;
You should replace database_name
with the name that you want for the new database.
Create database example
The following SQL statement creates a database called "demo".
Example
CREATE DATABASE demo;
Output
The output means that the statement is executed succesfully.
View the created database
You can use the following SQL statement to view a list of all existing databases.
Example
SHOW DATABASES;
Output
Database |
---|
demo |
sakila |
sys |
world |
.... |
MySQL Workbench created database
To view the newly created database "demo" in MySQL Workbench you should click on the refresh button as follows.
Best way to create a database
In general, when creating a new database it's recommended to use the optional clause IF NOT EXISTS
to be sure that the statement will execute only if the database is not already exist.
You cannot create 2 databases with the same name on the same database server.
If you try to create the "demo" database again without the optional clause IF NOT EXISTS
, you will get an error as follows.
Example
CREATE DATABASE demo;
Output
However, if you try to recreate the "demo" database with the optional clause IF NOT EXISTS
, you will get a warning message.
Example
CREATE DATABASE IF NOT EXISTS demo;
Output
Error vs Warning in SQL
If you have a several SQL statements and you want to execute all of them, you may face an error in one them or you may see some warning messages.
In case of Error
If there is an error in a specific statement, all the statements after the statement that cause the error will not be executed.
In case of Warning
If the Database Server shows you a warning message(s) about a specific statment(s), it will execute the statements after normally.