There are different methods to know the name of the current user in MySQL. There can be many reasons we want to know who is the current user. Here is list of the of the few of the such reasons.
- Customized code which we want to run based on the reason.
- Checking the permissions based on the user.
- Inserting the name of the user in the audit table.
- Displaying special message based on the login user.
- Executing some special logic/code based on the logged in user.
Method 1: Usage of system functions
SELECT user(); SELECT current_user();
Both the above SELECT statements return the name of the current user, which executes the above statements.
Method 2: Usage of system table
SELECT * from mysql.user;
The above lists out all the users registered in the server. It will also list out various levels of privileges for the users.
To get only the information about the current user, you can use
SELECT * from mysql.user WHERE user() like concat(user,'%');
You can also use synonym functions of user()
SELECT session_user(); SELECT system_user();
Both the above will return the result which is also the result of SELECT user().
If you are using a similar login in your application or business, I would like to know what is the business need for the same. Please leave a comment.
Reference: Pinal Dave (https://blog.sqlauthority.com)