SQL CREATE DATABASE Statement
The CREATE DATABASE
statement is used to create a new SQL database.
Syntax
The basic syntax for the CREATE DATABASE
statement is as follows:
CREATE DATABASE database_name;
Note: Be sure that the database name is unique within the database system.
Create DATABASE - Example
The following SQL statement will create a database called "demo_db":
CREATE DATABASE demo_db;
After creating a database, we ask SQL to use this that database using the following command:
USE demo_db
After the execution, SQL will set the "demo_db" database as a target for all future commands.
Note: In unit, the database and table names are case-sensitive, so we must always refer to the database name with a lower case. In our example, it will be "demo_db".
Create Database in MariaDB / MySQL steps
Here we will create a database in MySQL using the command line.
Step 1: Invoking the command-line tool
In MySQL, to invoke the command line, we have to log in to the MySQL server first.
The following command will log in as a root
user.
shell> mysql -u root -p
After the execution, you will be prompted for the password. Enter the password for the root
user, if it is correct, the mysql>
prompt will appear, which will allow us to execute our SQL queries.
Step 2: Creating a Database
Now, we will create a new database called "demo_db" by executing the following command:
mysql> CREATE DATABASE demo_db
If the database created successfully, you would see the following output:
Query OK, 1 row affected (0.01 sec)
To avoid the error when you try the create a database that already exists. You can use the optional clause IF NOT EXISTS
as follows:
mysql> CREATE DATABASE IF NOT EXISTS demo_db
Step 3: Selecting the Database
At this stage, the database "demo_db" is created and ready for use.
Before using the database, you must select the database by running the following command:
mysql> USE demo_db;
To show all the existing database in MySQL, you can execute the following command:
mysql> SHOW DATABASES;