The following steps describe the procedure to reset the MySQL root password on Linux. The same procedure works for MariaDB too.
1) Stop the MySQL server
service mysql stop
2) Start the MySQL server manually without permission tables which allows us to login as root user without password:
mysqld_safe --skip-grant-tables &
3) Login into MySQL as root user without a password and switch to the "mysql" database:
mysql -u root mysql
Then execute this SQL query to set a new password for the MySQL root user:
use mysql; update user set Password=PASSWORD('mynewpassword') WHERE User='root';
On MySQL 5.7 and newer, use this query instead:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'mynewpassword';
(Replace "mynewpassword" with the new root password in the above command).
Then logout from the MySQL prompt by typing:
exit
4) Now bring back the running MySQL instance into the foreground by typing:
fg
and then press [ctrl] + c to kill the MySQL process.
5) Finally, start the MySQL server again:
service mysql start