How to Create MYSQL Database Using Shell Command?

Linux supports various database systems, and among them, MySQL is the most popular due to ease of access, better usability, more features, and better security. Every Linux administrator needs a database to manage large data. Since the command line is one of the major advantages of Linux because everything can be done from the commands.

This guide discusses the methods to create a MySQL database from the shell command on Linux.

  • How to Create a MySQL Database From the Shell Command?
  • Install MySQL Database 
  • Create MYSQL Database
  • View the Created Database
  • Bonus Tip: Remove MYSQL Database

How to Create a MySQL Database From the Shell Command in Linux?

To create a MySQL database using the shell command, use the mysql command as below:

Syntax:

$ mysql -u username -p -e "CREATE DATABASE dbname;"

The description of the above syntax is given below:

  • mysql invokes the command.
  • -u is the option saying that the following is the username.
  • -p stands for password.
  • -e specifies to execute the command and quit.
  • Create DATABASE dbname” is the query to create a new database with the name “dbname”.

How to Install MySQL on Linux?

Before moving any further, Install MySQL using these commands if it is not installed:

$ sudo apt install mysql-server      #Ubuntu/Debian
$ sudo yum install mysql-server      #RedHat/CentOS
$ sudo pacman -S mysql          #Arch Linux

The above image confirms the installation of MySQL on Ubuntu 22.04 LTS.

Create MYSQL Database 

Let’s create a database named “dbname” for the “root” user by using this command:

$ mysql -u root -p -e "CREATE DATABASE dbname;"

The above command creates a new MySQL database named “dbname”.

View the Created Database

To view the created database, use the “mysql” command, but first understand it:

  • -u specifies the username.
  • root is the username.
  • -p prompts to enter the password.
  • -e stands for execute.
  • “SHOW DATABASES;” is the query to display all databases created by user ‘root.’
$ sudo mysql -u root -p -e "SHOW DATABASES;"

The above image shows a list of databases on the system, and the “dbname” is the recently created database.

Note: If you have created a database using a non-root user (with no root privileges), use the above commands without the “sudo” keyword.

How to Remove MYSQL Database From Shell Command?

If you want to get rid of a MySQL database, here is the command that deletes the specified database:

$ sudo mysql -u root -p -e "DROP DATABASE dbname;"

Conclusion

The format <mysql -u username -p -e “CREATE DATABASE dbname;”> creates a database without logging in to the MySQL server. However, it requires a password, but using the “-e” flag, the database is created from the terminal and quits. To view the created database, use the <sudo mysql -u root -p -e “SHOW DATABASES;”> command. This guide explained how to create a database from a shell command on Linux.