MySQL is an open-source relational database management system commonly deployed as part of the LAMP stack (which stands for Linux, Apache, MySQL, and PHP) and, as of this writing, is the most popular open-source database in the world.
CREATE USER: Use CREATE USER 'username'@'host' IDENTIFIED BY 'password' to add new database users, specifying the hostname (like localhost or % for any host) to control where users can connect from.GRANT: Assign specific permissions using GRANT privilege ON database.table TO 'username'@'host', following the principle of least privilege by granting only the permissions each user needs.caching_sha2_password (MySQL 8.0 default) for secure password authentication, mysql_native_password for PHP compatibility, or auth_socket for local-only access without passwords.SHOW GRANTS to review permissions, REVOKE to remove privileges, and DROP USER to delete accounts. Always revoke privileges before dropping users in production.%, and resolve Error 1396 (user exists) by checking and dropping existing accounts first.In order to follow along with this guide, you’ll need access to a MySQL database. This guide assumes that this database is installed on a virtual private server running Ubuntu, though the principles it outlines should be applicable regardless of how you access your database.
If you don’t have access to a MySQL database and would like to set one up yourself, you can follow one of our guides on How To Install MySQL. Again, regardless of your server’s underlying operating system, the methods for creating a new MySQL user and granting them permissions will generally be the same.
You could alternatively spin up a MySQL database managed by a cloud provider. For details on how to spin up a DigitalOcean Managed Database, see our product documentation.
Please note that any portions of example commands that you need to change or customize will be shown as placeholders (like username, host, password, etc.) throughout this guide.
Upon installation, MySQL creates a root user account which you can use to manage your database. This user has full privileges over the MySQL server, meaning it has complete control over every database, table, user, and so on. Because of this, it’s best to avoid using this account outside of administrative functions. This step outlines how to use the root MySQL user to create a new user account and grant it privileges.
In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This plugin requires that the name of the operating system user that invokes the MySQL client matches the name of the MySQL user specified in the command. This means that you need to precede the mysql command with sudo to invoke it with the privileges of the root Ubuntu user in order to gain access to the root MySQL user:
- sudo mysql
Note: If your root MySQL user is configured to authenticate with a password, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating with the correct password:
- mysql -u root -p
Once you have access to the MySQL prompt, you can create a new user with a CREATE USER statement. The general syntax is:
- CREATE USER 'username'@'host' IDENTIFIED WITH authentication_plugin BY 'password';
After CREATE USER, you specify a username. This is immediately followed by an @ sign and then the hostname from which this user will connect. If you only plan to access this user locally from your Ubuntu server, you can specify localhost. Wrapping both the username and host in single quotes isn’t always necessary, but doing so can help to prevent errors.
You have several options when it comes to choosing your user’s authentication plugin. The following table compares the main authentication methods:
| Authentication Plugin | Security | Remote Access | Use Case | Compatibility |
|---|---|---|---|---|
caching_sha2_password |
Strong (SHA-256) | Yes | Default for MySQL 8.0+, recommended for new applications | Most modern clients |
mysql_native_password |
Good (SHA-1) | Yes | Legacy compatibility, PHP applications (phpMyAdmin) | Older clients, PHP < 7.4 |
auth_socket |
Strong (OS-based) | No | Local-only access, no password required | Ubuntu/Debian systems only |
The auth_socket plugin mentioned previously can be convenient, as it provides strong security without requiring valid users to enter a password to access the database. But it also prevents remote connections, which can complicate things when external programs need to interact with MySQL.
As an alternative, you can leave out the WITH authentication_plugin portion of the syntax entirely to have the user authenticate with MySQL’s default plugin, caching_sha2_password. The MySQL documentation recommends this plugin for users who want to log in with a password due to its strong security features.
Run the following command to create a user that authenticates with caching_sha2_password. Be sure to change sammy to your preferred username and password to a strong password of your choosing:
- CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
Note: There is a known issue with some versions of PHP that causes problems with caching_sha2_password. If you plan to use this database with a PHP application — phpMyAdmin, for example — you may want to create a user that will authenticate with the older, though still secure, mysql_native_password plugin instead:
- CREATE USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
If you aren’t sure, you can always create a user that authenticates with caching_sha2_password and then ALTER it later on with this command:
- ALTER USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
After creating your new user, you can grant them the appropriate privileges.
The general syntax for granting user privileges is as follows:
- GRANT PRIVILEGE ON database.table TO 'username'@'host';
The PRIVILEGE value in this example syntax defines what actions the user is allowed to perform on the specified database and table. You can grant multiple privileges to the same user in one command by separating each with a comma. You can also grant a user privileges globally by entering asterisks (*) in place of the database and table names. In SQL, asterisks are special characters used to represent “all” databases or tables.
To illustrate, the following command grants a user global privileges to CREATE, ALTER, and DROP databases, tables, and users, as well as the power to INSERT, UPDATE, and DELETE data from any table on the server. It also grants the user the ability to query data with SELECT, create foreign keys with the REFERENCES keyword, and perform FLUSH operations with the RELOAD privilege. However, you should only grant users the permissions they need, so feel free to adjust your own user’s privileges as necessary.
You can find the full list of available privileges in the official MySQL documentation.
Run this GRANT statement, replacing sammy with your own MySQL user’s name, to grant these privileges to your user:
- GRANT CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT, REFERENCES, RELOAD on *.* TO 'sammy'@'localhost' WITH GRANT OPTION;
Note that this statement also includes WITH GRANT OPTION. This will allow your MySQL user to grant any permissions that it has to other users on the system.
Warning: Some users may want to grant their MySQL user the ALL PRIVILEGES privilege, which will provide them with broad superuser privileges akin to the root user’s privileges, like so:
- GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;
Such broad privileges should not be granted lightly, as anyone with access to this MySQL user will have complete control over every database on the server.
Many guides suggest running the FLUSH PRIVILEGES command immediately after a CREATE USER or GRANT statement in order to reload the grant tables to ensure that the new privileges are put into effect:
- FLUSH PRIVILEGES;
However, according to the official MySQL documentation, when you modify the grant tables indirectly with an account management statement like GRANT, the database will reload the grant tables immediately into memory, meaning that the FLUSH PRIVILEGES command isn’t necessary in our case. On the other hand, running it won’t have any negative effect on the system.
If you need to revoke a permission, the structure is almost identical to granting it:
- REVOKE type_of_permission ON database_name.table_name FROM 'username'@'host';
Note that when revoking permissions, the syntax requires that you use FROM, instead of TO which you used when granting the permissions.
You can review a user’s current permissions by running the SHOW GRANTS command:
- SHOW GRANTS FOR 'username'@'host';
Just as you can delete databases with DROP, you can use DROP to delete a user:
- DROP USER 'username'@'localhost';
After creating your MySQL user and granting them privileges, you can exit the MySQL client:
- exit
In the future, to log in as your new MySQL user, you’d use a command like the following:
- mysql -u sammy -p
The -p flag will cause the MySQL client to prompt you for your MySQL user’s password in order to authenticate.
To remove a MySQL user, you can use the DROP USER command. The syntax for this command is as follows:
DROP USER 'username'@'host';
Replace username with the actual username you want to remove, and host with the hostname or IP address from which the user can connect. For example, to remove a user named ‘sammy’ who can connect from ‘localhost’, you would use:
DROP USER 'sammy'@'localhost';
After executing this command, the specified user will be removed from the MySQL server. Note that this action is irreversible, so make sure to use it with caution and only when you are certain you want to remove the user.
It’s also important to note that you cannot remove a user who is currently connected to the MySQL server. If you try to do so, you will receive an error message indicating that the user is still connected. You will need to disconnect the user before attempting to remove them.
The Access denied for user error occurs when a user attempts to connect to MySQL with incorrect credentials or insufficient privileges. Fix it by verifying credentials and granting the necessary privileges.
To fix this error, follow these steps:
Verify user credentials: Ensure that the username, password, and host are correct. Double-check that the username and password are spelled correctly and that the host is set to the correct value (e.g., ‘localhost’, ‘%’, or a specific IP address).
Check privileges: Ensure that the user has been granted the necessary privileges to access the database. You can do this by running the SHOW GRANTS command to review the user’s current permissions:
SHOW GRANTS FOR 'username'@'localhost';
This will display the current privileges granted to the user. If the user lacks the necessary privileges, you can grant them using the GRANT command.
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
Or, to grant privileges on a specific table:
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.table_name TO 'username'@'localhost';
These steps resolve the Access denied for user error and ensure the user has the necessary access to the MySQL database.
Enable remote connections by granting privileges with the hostname set to % (any host) or a specific IP address. For example:
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%';
This grants all privileges to the user ‘username’ from any host (%).
Error 1396 occurs when trying to create a user that already exists. Check if the user exists, then either modify the existing account or drop it before creating a new one.
To check if a user already exists, use the following command:
SELECT * FROM mysql.user WHERE User = 'newuser';
If the user exists, drop the existing user account:
DROP USER 'newuser'@'%';
Then create the new user account:
CREATE USER 'newuser'@'%' IDENTIFIED BY 'password';
Create a MySQL user with limited privileges by specifying only the privileges needed. For example, to grant SELECT, INSERT, UPDATE, and DELETE privileges on a specific database:
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.* TO 'username'@'localhost';
This approach ensures that the user can only perform the specified actions on the specified database, limiting their privileges.
Check MySQL user permissions using the SHOW GRANTS command. The syntax is:
SHOW GRANTS FOR 'username'@'localhost';
This command will display all the privileges granted to the specified user.
GRANT ALL PRIVILEGES grants a user all available privileges on a database or table, whereas specific privileges limit the user’s access to only the specified actions. Granting all privileges can be a security risk, as it gives the user complete control over the database or table. On the other hand, granting specific privileges ensures that the user can only perform the actions necessary for their role, reducing the risk of unauthorized access or changes.
Allow remote access by granting privileges with the hostname set to % (any host). For example:
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%';
This grants all privileges to the user from any host, allowing remote access.
Delete a MySQL user safely by first revoking all privileges, then dropping the user account:
REVOKE ALL PRIVILEGES ON *.* FROM 'username'@'localhost';
DROP USER 'username'@'localhost';
This approach ensures that the user account is removed safely, without leaving any lingering privileges that could be exploited.
By following this tutorial, you’ve learned how to add new users and grant them a variety of permissions in a MySQL database. From here, you could continue to explore and experiment with different permissions settings for your MySQL user, or you may want to learn more about some higher-level MySQL configurations.
For more information about the basics of MySQL, you can check out the following tutorials:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Former Director of Community at DigitalOcean. Expert in cloud topics including LAMP Stack, CentOS, Ubuntu, MySQL, SSL certificates, and more.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
You can grant multiple privileges in one command by separating them with commas: eg: “GRANT UPDATE, SELECT ON [database name].[table name] TO ‘[username]’@‘localhost’;”
This code from above has a backtick before localhost. It should be a single quote.
GRANT ALL PRIVILEGES ON * . * TO ‘newuser’@‘localhost’;
Hi, nice intro. It was useful. I noticed that for the REVOKE command, one has to use FROM, not TO. Also, might be helpful for new users to know that they can use ‘%’ as a wildcard instead of ‘localhost’.
This worked for me. However to be able to use MySql Workbench it seems it wants another version of the user. I needed to do the following (which has taken me a few hours of playing around with to get right) mysql> select user,host from mysql.user; <–to see users mysql> GRANT ALL ON . to user@’%’ IDENTIFIED BY ‘user-pwd’; mysql> FLUSH PRIVILEGES; mysql> select user,host from mysql.user; mysql>quit Also need to comment out or change the bind-address to <droplet address>. This does reduce security. sudo nano /etc/mysql/my.cnf ;bind-address=127.0.0.1 exit and $service mysql start $service mysql stop
then get access on <droplet-ip> from my Sql workbench using user/user-pwd on std port for adminstering, creating and querying.
There’s no link at the start of this tutorial to the first tutorial. Can you please add that link?
how to give permission to only select views in requried user pls send me urgent
@ravuri.srinivasarao7: Please read the second part of the article: “How To Grant Different User Permissions”
Is there a way to just give permission to create a new table within the specified database, but not allow the creation of a new database?
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.