SQL Create Database

Creating a Database

To begin working with data, the first step is to create a database. It's assumed that you have access to MySQL or SQL Server and necessary privileges. If not, refer to the getting started guide.

The SQL CREATE DATABASE statement is used to create a database.

Syntax

Here's the basic syntax for creating a database:

CREATE DATABASE database_name;

The following SQL statement demonstrates creating a database named demo:

CREATE DATABASE demo;

Creating a database doesn't automatically select it for use. Therefore, before proceeding, use the USE statement to select the desired database. For instance, USE demo; sets the demo database as the target for all subsequent commands.

Note: On Unix systems, database and table names are case-sensitive. Therefore, always refer to your database as demo, not as Demo, DEMO, or any other variation. However, SQL keywords are case-insensitive, meaning CREATE DATABASE is equivalent to create database.


Creating Database in MySQL

Let's create a database in MySQL using the command-line tool.

Step 1: Invoke the MySQL command-line tool

To start using the MySQL command line, you need to log in to the MySQL server first. Use the following command in your terminal, and when prompted, enter your password for the root user. If correct, the mysql> prompt will appear, allowing you to execute SQL commands and view results.

shell> mysql -u root -p

Step 2: Creating a MySQL Database

Now, execute the following command to create a database named demo.

mysql> CREATE DATABASE demo;

If the database is created successfully, you'll see output similar to this:

Query OK, 1 row affected (0.03 sec)

If you attempt to create a database that already exists, an error message will be displayed. To avoid this in MySQL, you can use the optional clause IF NOT EXISTS as shown below:

mysql> CREATE DATABASE IF NOT EXISTS demo;

Step 3: Selecting the Database

Enter the following command and press enter. You'll see the output "Database changed". Now, the demo database is selected as the default database for all future operations.

mysql> USE demo;

Tip: To view a list of existing databases on the MySQL server, use the command SHOW DATABASES; in the command line.