Rostyslav Rava - Personal Website

How to Change a User Password in MySQL

Changing a MySQL user password is always a good idea. It is often done periodically for credential rotation. It can also respond to compromised credentials, for example, when a password is committed by mistake to a code repository.

First, identify the user whose password needs to be changed. In MySQL, users are identified by a username and the host from which they are allowed to connect. In most cases, the host is % (any host) or localhost.

The appropriate username and host can be retrieved from the list of all MySQL users:

SELECT user, host FROM mysql.user;

This produces output like the following:

+------+-----------+
| user | host      |
+------+-----------+
| root | localhost |
| ...  | ...       |
+------+-----------+

Then change the password with:

ALTER USER 'username'@'localhost' IDENTIFIED BY 'new_password';

Replace username with the actual username, localhost with the host, and new_password with the new password.

For example, to change the password for root on localhost:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'N3wPa$$w0rd';

Reconnect to MySQL and verify that the new credentials work:

mysql -u root -h localhost -p

If the user is used by an application, update the connection string after you confirm the new credentials work.

This post showed how to identify a MySQL user by username and host and change the password.

Tags:

Last updated: