Read in 3 minutes
How to Create a MySQL Database on Linux via Command Line
MySQL is the most popular open-source relational database management system.
This tutorial explains how to create MySQL or MariaDB databases through the command line.
Before you begin
We are assuming that you already have MySQL or MariaDB server installed on your system.
If you don’t have MySQL or MariaDB installed on your server, you can quickly install it by following the tutorials below:
- How To Install MySQL on CentOS 7, Ubuntu 18.04, Debian 9.
- How To Install MariaDB on CentOS 7, Ubuntu 18.04, Debian 9
All commands are executed as an administrative user (the minimum privilege required to create a new database is
CREATE) or with a root account.
To access the MySQL shell type the following command and enter your MySQL root user password when prompted:
mysql -u root -p
If you haven’t set a password for your MySQL root user you can omit the
Create a MySQL Database
Creating a new MySQL Database is as simple as running a single command.
To create a new MySQL or MariaDB database issue the following command, where
database_name is the name of the database you want to create:
CREATE DATABASE database_name;
Query OK, 1 row affected (0.00 sec)
If you try to create a database that already exists you will see the following error message:
ERROR 1007 (HY000): Can't create database 'database_name'; database exists
To avoid errors if the database with the same name as you are trying to create exists you can use the following command:
CREATE DATABASE IF NOT EXISTS database_name;
Query OK, 1 row affected, 1 warning (0.00 sec)
In the output above, you can see
Query OK which means that the query was successful, and
1 warning which tells us that the database already exists and no new database was created.
View All MySQL Databases
To view the database you’ve created, from within the MySQL shell execute the following command:
The command above will print a list of all databases on the server. The output should be similar to this:
+--------------------+ | Database | +--------------------+ | information_schema | | database_name | | mysql | | performance_schema | | test | +--------------------+ 5 rows in set (0.00 sec)
Select a MySQL Database
When you create a database, the new database is not selected for use. To select a database before you begin a MySQL session, use the following command:
Once you select a database, all the subsequent operations such as creating tables will be performed on the selected database.
Create a MySQL Database with mysqladmin
You can also create a new MySQL database from the Linux terminal by using the mysqladmin utility.
For example, to create a database named
database_name, type the following command and enter your MySQL root user password when prompted:
mysqladmin -u root -p create database_name
You have learned how to create MySQL databases.
Feel free to leave a comment if you have any questions.