SQL Create Database

We assume that you already have a database server, like MySQL or SQL Server, on which you can run SQL queries.

If you don't have a database server available, check out the SQL Getting Started for details.

In order to work with data, the first thing we need is a database.

Create Database

Here is the basic syntax for creating a database.

CREATE DATABASE database_name;

The below SQL query creates a database with the name "demo". See SQL Syntax for guidelines.

CREATE DATABASE demo;

Create Database If Not Exists

In case, the database already exists, the above query gives an error, which can be avoided by including the IF NOT EXISTS keyword.

CREATE DATABASE IF NOT EXISTS demo;

Select Database

After creating the database, we need to select it as the target database using the USE keyword as shown below.

  • All the further SQL queries are executed on the selected target database.
USE demo;

Create Database in MySQL using Terminal

If we are using Unix or Linux distribution systems for SQL servers, then we need to access the MySQL database using a terminal as explained below.

  • Login to the machine using a terminal, using tools like PUTTY.
  • Then, log in to the MySQL command-line tool, which changes the prompt from the respective shell to mysql upon successful login.
  • Then, create and select a database.

Invoke the MySQL command-line

After successful login into the machine terminal, execute the below command to login into MySQL as a root user.

shell> mysql -u root -p

Create a database

After successful MySQL login, the prompt will be changed to mysql, where we can run any SQL queries.

mysql> CREATE DATABASE demo;

Select the database

After the successful creation of the demo database, run the below command to change the target database to "demo" so that all the further queries run on this database.

mysql> USE demo;

Overall

We now know how to create a database on a database server.

Related Links