Reset MySQL/MariaDB Root Password

You've been locked out of your MySQL or MariaDB root account. Maybe you forgot the password, or it was never set. Here's how to reset it safely.

Stop the database service

First, stop the running database server so we can restart it in a special mode that bypasses authentication.

sudo systemctl stop mariadb

If you're running MySQL instead of MariaDB, use mysql as the service name:

sudo systemctl stop mysql

Start in safe mode

Start the database server with grant tables disabled and networking off. This lets you connect as root without a password, and the --skip-networking flag ensures no remote connections can be made during this window.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Wait a few seconds for the server to start. You'll see output indicating the server is ready.

Connect without a password

Now connect to the database as root. Since grant tables are disabled, no password is required.

mysql -u root

You should see the MariaDB or MySQL prompt.

Reset the password

Re-enable the privilege system and set a new root password. For MariaDB 10.4+ and MySQL 5.7+:

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'YourNewPassword';

For older MySQL versions (5.6 and below), use this syntax instead:

FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('YourNewPassword');

Replace YourNewPassword with a strong password. Then exit:

EXIT;

Restart normally

Kill the safe-mode process and start the service normally:

sudo kill $(cat /var/run/mysqld/mysqld.pid)
sudo systemctl start mariadb

If the PID file doesn't exist, find the process with sudo pgrep -f mysqld_safe and kill it manually.

Verify

Test that the new password works:

mysql -u root -p

Enter your new password at the prompt. If you see the database shell, the reset was successful.