Open In App

MySQL | Change User Password

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Changing user passwords in MySQL is a common task for database administrators, ensuring the security of the database system. There are multiple ways to change a users password in MySQL, depending on our requirements and permissions. In this article, We will learn three methods to change a user's password such as using the SET PASSWORD statement, the ALTER USER statement, and the UPDATE statement.

How to Change User Password in MySQL?

Let's learn how to change the user password in SQL. In MySQL, the user account password can be changed using three different statements.

  1. SET PASSWORD statement
  2. ALTER USER statement
  3. UPDATE statement

1. Changing MySQL User Password Using The SET PASSWORD Statement

To change the user password using the SET PASSWORD statement the first requirement is that the account needs to have at least UPDATE privilege.

The user account should be in the "user@host" format whose password you want to update.

Syntax:

SET PASSWORD FOR 'username'@'host' = 'newpassword';

Example: To change the password for the user account 'gfguser1' connecting from 'localhost' to 'newpass'.

Query:

SET PASSWORD FOR 'gfguser1'@'localhost' = 'newpass';

2. Changing MySQL User Password Using The ALTER USER statement

The second way to change the password for a user account is to use the ALTER USER statement. The ALTER USER statement is used along with the "IDENTIFIED BY" clause.

Syntax:

ALTER USER 'username'@'host' IDENTIFIED BY 'newpassword';

Example: To change the password for the user account 'gfguser1' connecting from 'localhost' to 'newpass'.

Query:

ALTER USER 'gfguser1'@'localhost' IDENTIFIED BY 'newpass';

3. Changing MySQL User Password Using UPDATE Statement

The third way to change the password of a user account is by using the UPDATE statement. The Update statement updates the user table of the MySQL database.

The FLUSH PRIVILEGES statement needs to be executed after executing the UPDATE Statement. The FLUSH PRIVILEGES statement is used to reload privileges from the grant table in the MySQL database.

Syntax:

UPDATE mysql.user 
SET authentication_string = PASSWORD('newpassword')
WHERE User = 'username' AND Host = 'host';
FLUSH PRIVILEGES;

Example: To change the password for the user account 'gfguser1' connecting from 'localhost' to 'newpass'.

Query:

UPDATE mysql.user 
SET authentication_string = PASSWORD('newpass')
WHERE User = 'gfguser1' AND Host = 'localhost';
FLUSH PRIVILEGES;

Conclusion

Changing user passwords in MySQL can be done using the SET PASSWORD, ALTER USER, or UPDATE statements, depending on the situation. These methods ensure that user accounts remain secure by updating their passwords when needed. It is essential to use the correct statement based on your permissions and requirements.


Next Article
Article Tags :
Practice Tags :

Similar Reads