An account that uses MySQL database, MySQL considers as a MySQL database user. MySQL defines a user as a username and client host or hosts that the user can use to connect to the server.
MySQL uses the “user” table of the MySQL system database. You need MySQL Administrator or root-level access to be able to query the user table. The user table consists of the following information.
The account also has password information. Depending on the Operating system, MySQL has restrictions on the username and passwords. They are as follows
To create a user, we use the “Create USER” statement.
The basic syntax of creating a user is as follows:
CREATE USER [IF NOT EXISTS] account_name
IDENTIFIED BY 'password';
The steps to create a user are as follows:
Login to MySQL server as a root user. Trigger the Query :
select user from mysql.user;
This lists all the users that are already present. Next, write the query to create a user. First, we will create a user without a hostname
create user sysadmin_user1 identified by 'password1';
We can select again and see that the user is created.
Next, we will create a user with a hostname. The Query to do so is:
create user test_user@localhost identified by 'password2';
To drop a user, we need to log in with the root login. To remove an account from MySQL, we use the ‘DROP User
’ statement.
The basic syntax is:
DROP USER account_name;
We can also drop multiple users by separating the names by a comma(,
)
Dropping a user that does not exist, causes MySQL to throw an error. To circumvent that, we have the syntax:
DROP USER [IF EXISTS] account_name;
While dropping users, we need to specify the hostname if a hostname is attached to the user.
To drop a user in MySQL, the steps are as follows:
Login to MySQL client as root user credentials. Trigger the query to select the users,
select user from mysql.user;
To drop a user with a specific hostname
drop user test_user@localhost;
If we try to drop the above user without the hostname, MySQL will throw an error, as shown in the screenshot below.
To drop a user without a specific hostname, i.e., % attached to it, we can drop the user as
drop user sysadmin_user1;
If we try to drop a user that does not exist and do not use the “If exists” clause, MySQL throws an error, as shown in the screenshot below.
If we use the “If exists” clause, MySQL does not drop any users but suppresses the error.
To know what are all the hostnames are attached to the user, we can use the below query.
select user, host from mysql.user;