How to change MySQL root password

Let's learn how you can change your MySQL root password

Posted on October 06, 2021

To change your MySQL root password, you need to use either the ALTER USER or SET PASSWORD statement as follows:

ALTER USER root@localhost IDENTIFIED BY 'newPassword';
-- or
SET PASSWORD FOR root@localhost = 'newPassword';

If you’re currently logged in as the root account, you can even omit the FOR clause in your SET PASSWORD statement as shown below:

-- change the current user account password
SET PASSWORD = 'newPassword';

If you forgot your current root password and can’t connect to the MySQL server, then you need to reset the root password with another method.

Resetting root password for Windows and Unix

Resetting a root password requires you to restart your MySQL server and add the --init-file option to the sqld command.

The --init-file option is used to provide an initialization file. The file should contain SQL statements that you want to run during the startup process.

If you’re using Windows, then you need to create an init.txt file with the following content:

ALTER USER root@localhost IDENTIFIED BY 'newPassword';

Next, stop the currently running MySQL service.

After that, you need to restart the service using mysqld --init-file=init.txt command. Keep in mind that you need to provide the absolute path to the init file.

The full working example may look as follows:

mysqld --init-file=C:\\init.txt

Once the server has started, you can test connecting to the MySQL server using the root account.

Don’t forget to delete the init.txt file as well to prevent others from finding out your root password.

The method above should work both for Windows and Unix-like operating systems.

Related articles:

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.