Managing users and their privileges is an essential aspect of MySQL administration. This involves creating, modifying, and removing users, as well as managing their access rights to databases and tables.
You can create a new user in MySQL using the CREATE USER command. A user account in MySQL is identified by a combination of the username and host (where the user can connect from).
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
CREATE USER 'john'@'localhost' IDENTIFIED BY 'john_password';
This creates a user named john who can connect to the MySQL server from the local machine (localhost) using the password john_password.
Once a user is created, you need to assign permissions that control what the user can do in MySQL. permissions determine what actions a user can perform, such as selecting data, creating tables, or managing the entire database.
GRANT privilege_type ON database_name.table_name TO 'username'@'host';
To give john permission to perform all actions on a specific database (employees):
GRANT ALL PRIVILEGES ON employees.* TO 'john'@'localhost';
To give only read (SELECT) access:
GRANT SELECT ON employees.* TO 'john'@'localhost';
After granting privileges, it’s good practice to reload the privileges with:
FLUSH PRIVILEGES;
To view what rightsa user has been granted, you can use the SHOW GRANTS command.
SHOW GRANTS FOR 'username'@'host';
SHOW GRANTS FOR 'john'@'localhost';
GRANT ALL PRIVILEGES ON `employees`.* TO 'john'@'localhost'
You can change a user's password using the ALTER USER or SET PASSWORD commands.
ALTER USER 'username'@'host' IDENTIFIED BY 'new_password';
ALTER USER 'john'@'localhost' IDENTIFIED BY 'new_secure_password';
To remove a user from MySQL, you can use the DROP USER command.
DROP USER 'username'@'host';
DROP USER 'john'@'localhost';
This will delete the john user and revoke all their privileges.
Privilege Type | Description |
---|---|
ALL PRIVILEGES | Grants all privileges to a user. |
SELECT | Allows reading from tables (using SELECT). |
INSERT | Allows inserting rows into tables. |
UPDATE | Allows updating existing data in tables. |
DELETE | Allows deleting rows from tables. |
CREATE | Allows creating new databases and tables. |
DROP | Allows deleting databases and tables. |
ALTER | Allows modifying the structure of tables. |
GRANT OPTION | Allows a user to grant privileges to other users. |