In this tutorial we will look at how to change the MySQL root password in Ubuntu Linux if you have forgotten it or inherited a server and never knew it in the first place. To change the MySQL root password in Ubuntu you will need superuser privileges, i.e. root access, on the system. The following guide works on Ubuntu 10.04, 10.10, 11.04, 11.10, and possibly 12.04.
If you do know the root password but simply want to change it, have a look at our how to change MySQL user password tutorial.
Below are the steps to change the MySQL root password in Ubuntu. Ensure that you run the following commands as root (the Linux superuser, not to be confused with the MySQL admin user).
1) Execute the following to stop the MySQL server:
service mysql stop
Expected result:
2) Start a temporary MySQL server in a mode that will make it not ask for a password. The ampersand (&) at the end of the command is a Bash operator which tells the shell to execute the command in the background in a subshell. (If we didn't use the & symbol the server would be started in the foreground in our shell and we wouldn't be able to run any more commands till it was terminated.)
mysqld_safe --skip-grant-tables &
Expect a result like:
Note the job number in square brackets (in this case 1), we will need it later.
3) Connect to the temporary MySQL server we just started using the regular MySQL client without a password:
mysql -u root
Expect a result like:
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
4) Run a MySQL Update Query on the mysql.user table to change the root password, flush privileges for the changes to take effect and then quit:
UPDATE mysql.user SET password = PASSWORD('newrootpassword') WHERE User = 'root'; FLUSH PRIVILEGES; quit
The queries should execute successfully and then you should get:
At this point the password has been changed and we have logged out of the MySQL server.
5) Now we will need to terminate the temporary MySQL server we started. Recall the job number which you noted from Step 2 above. If you forgot to note it, execute:
jobs
Expect a result like:
Then execute:
kill %1
Where 1 is the job number identifying the "mysqld_safe --skip-grant-tables &" job. The result is:
Now there is no MySQL server running.
6) Start the regular MySQL server:
service mysql start
Expect a result like:
7) Login with your new MySQL password:
mysql -u root -p
And that is it. You should now be successfully logged in to the MySQL server.
And that is how you change the MySQL root password in Ubuntu if you have forgotten it. We know you found this tutorial useful :-)
Let us know that it works for you by leaving a comment below.