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
--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
The full working example may look as follows:
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.