How to fix if can’t access MySQL without SUDO?

Its happend recently after I reinstall my OS and development environment. But, I’ve fix this after search some references from many source. Now, I’ll write here so when sometimes I forgot the way, I can read this, but it’s more better if its also can help for you.

sutriman@biskom154:~$ mysql -u root -p
Enter password: 
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Its always denied if we run the command without sudo, but when we run it using sudo, its working

sudo mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Its happend because in MariaDB on Debian/Ubuntu by default authenticates via Unix sockets and it checks the effective unix user id of the user calling mysql. If you don’t run mysql as root (or with sudo) this fails.

To change it back to clasic method, we can login mysql using sudo, and then

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';
FLUSH PRIVILEGES;

Its working for me..

source: https://unix.stackexchange.com/questions/396738/cant-access-mysql-without-running-sudo