How To Create Users and Grant Privileges in MySQL
- By : Mydatahack
- Category : DBA, Infrastructure
- Tags: DBA, MySQL, Permissions, User
Managing user access in MySQL is similar to Postgres (see Postgres user creation here). You can either manage the access privileges through roles or give privileges directly to users.
This post is a quick reference for granting privileges to users. Let’s have a look at a simple use case.
We would like to create a user called writer with full access to test, usermanaged, datamart, and staging schemas and read only access to sakila, sys and world schemas.
First of all, let’s create the user with password.
1 | CREATE USER 'writer' IDENTIFIED BY 'Password1'; |
Now, we can add privileges to the user. MySQL does not allow to have a list of databases in the grant statement. You need to do it by schema. For the table, you can use the wild card asterisk.
1 2 3 4 5 6 7 | GRANT ALL Privileges ON test.* TO 'writer'; GRANT ALL Privileges ON usermanaged.* TO 'writer'; GRANT ALL Privileges ON datamart.* TO 'writer'; GRANT ALL Privileges ON staging.* TO 'writer'; GRANT SELECT ON sakila.* TO 'writer'; GRANT SELECT ON sys.* TO 'writer'; GRANT SELECT ON world.* TO 'writer'; |
We also create a read only user who only has read access to all schemas.
1 | CREATE USER 'readonly' IDENTIFIED BY 'Password1'; |
If the permission is given to all schemas and tables, we can use * as below.
1 | GRANT SELECT ON *.* TO 'readonly'; |
REFERENCE