Introduction
MySQL is an open-source database management system based on SQL- Structured Query Language. It helps users store, organize and retrieve data. It has a variety of operations to grant specific permissions to different users within the table and database.
When MySQL server installation completes, it includes options of managing through root user or specific user account only. But for security reasons, sometimes it becomes necessary to grant permission to other users without giving them complete control. In such cases, you need to create non-root users and grant them specific privileges and permissions to modify the database. In this article, we will discuss how to create new users and manage their permissions and privileges.
MySQL Create User
We can create a MySQL user with the following command:
CREATE USER ‘account_name’ IDENTIFIED BY 'password'; |
In the above query, the user will only be created only if it does not exist. The account_name has two parts; username, and hostname, separated by the '@' symbol.
Username is the name of the user, and hostname is the host's name from which the host can connect from the database server. So it is written like:
username@hostname. |
Here hostname is optional, and to connect with any host server; the user can use:
username@% |
Now let's discuss one example step by step to create a user in the MySQL server database.
Step 1. Open MySQL server using MySQL client tool.
Step 2. Enter the account password and hit enter.
Step 3. You can execute the following command to get the list of all users.
mysql> select user from mysql.user; |
The output will be similar to the output given below.
+-----------+ | user | +-----------+ | mysql.sys | | mysqlxsys | | root | +-----------+ 3 rows in set (0.00 sec) |
Step 4. Now to add a new user, execute the following query.
mysql> create user ninja@localhost identified by 'sqlninja'; |
A new user with the username 'ninja' will be created. When we again run the command to show the list of all users in the output, a new user will be added to the list.
+-----------+ | user | +-----------+ | mysql.sys | | mysqlxsys | | root | |ninja | +-----------+ 4 rows in set (0.00 sec) |
Step 5. We can also use the IF NOT EXISTS clause along with the above query to create a user only if it does not exist.
mysql> CREATE USER IF NOT EXISTS james@localhost IDENTIFIED BY 'ninjames'; |