How to create a MySQL database and assign a user on Linux

Managing multiple applications on a Linux server often requires separate MySQL users for each app. In this guide, you’ll learn how to create a MySQL database and assign a user with appropriate privileges — a common task for developers and system administrators.
Step-by-Step guide
1. Open the MySQL terminal
💡 On most systems, you can launch the MySQL terminal with superuser privileges using the following command:
sudo mysql -u root
2. Create a new database
Once inside the MySQL shell, create your new database with:
CREATE DATABASE `your_database_name`;
3. Create a new MySQL user
Create a user and define a secure password:
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'your_secure_password';
4. Grant privileges to the user
To grant access to all databases:
GRANT ALL PRIVILEGES ON *.* TO 'new_user'@'localhost';
To grant access to a specific database:
GRANT ALL PRIVILEGES ON your_database_name.* TO 'new_user'@'localhost';
5. Apply privilege changes
Make sure MySQL applies the changes immediately:
FLUSH PRIVILEGES;
Additional MySQL commands for user and database management
If you’re managing a MySQL instance, the following commands can come in handy for routine administration:
Show user privileges
SHOW GRANTS FOR 'username'@'localhost';
List all MySQL users
SELECT user, host FROM mysql.user;
List all databases
SHOW DATABASES;
Show the current logged-in user
SELECT current_user();
Delete a MySQL user
DROP USER 'username'@'localhost';
Revoke all user privileges
REVOKE ALL PRIVILEGES ON *.* FROM 'username'@'localhost';
Change a MySQL user password
ALTER USER 'username'@'localhost' IDENTIFIED BY 'new_password';