Create a MySQL/MariaDB database and user

Updated: 2022-04-02

This tutorial will help you set up a new database with a new user that has access to a specific database or all databases.

Note: Make sure you change new_mysql_database, new_mysql_user and new_mysql_password with something of your own and create a strong password.

Use the root user ONLY for administration purposes. By using the root user on production, you risk of having a system-wide security hole.

  1. Login to MySQL/MariaDB

Note: This command must be run as root, hence the sudo in front of it.

sudo mysql -u root -p

and press ENTER

  1. Create the database
CREATE DATABASE new_mysql_database;
  1. Create the user
CREATE USER 'new_mysql_user'@'localhost' IDENTIFIED BY 'new_mysql_password';
  1. Grant all privileges to a specific database
GRANT ALL PRIVILEGES ON new_mysql_database.* TO 'new_mysql_user'@'localhost';
  1. Grant all privileges to all databases (only if necessary)
GRANT ALL PRIVILEGES ON *.* TO 'new_mysql_user'@'localhost';
  1. Grant usage privileges to all databases (only if necessary)
GRANT USAGE ON *.* TO 'new_mysql_user'@'localhost';
  1. Flush the privileges
FLUSH PRIVILEGES;
  1. Check the new user (optional)
SHOW GRANTS FOR 'new_mysql_user'@'localhost';

Resources: