MySQL query to create user and grant permission


To create a user and grant permission, the syntax is as follows −

create database yourDatabaseName DEFAULT CHARACTER SET utf8;
create user `yourUserName` identified by yourPassword;
GRANT SELECT ON yourDatabaseName .* TO `yourUserName`;
GRANT INSERT ON yourDatabaseName .* TO `yourUserName`;
GRANT UPDATE ON yourDatabaseName .* TO `yourUserName`;
GRANT DELETE ON yourDatabaseName .* TO  `yourUserName`;
GRANT EXECUTE ON yourDatabaseName .* TO `yourUserName`;

Here is the query to create user and grant permission −

mysql> create database demo_app DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> create user `John_123` identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT SELECT ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT INSERT ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT UPDATE ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT DELETE ON demo.* TO  `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT EXECUTE ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)

Let us display all the grants of the above user:

mysql> show grants for `John_123`;

This will produce the following output −

+-----------------------------------------------------------------------------+
| Grants for John_123@%                                                       |
+-----------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `John_123`@`%`                                        |
| GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `demo`.* TO `John_123`@`%` |
+-----------------------------------------------------------------------------+
2 rows in set (0.00 sec)

Updated on: 31-Dec-2019

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements