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)
3 Comments. Leave new
Please post the results of Method-2. Also, why are there two commands for Method-1 when both of them display the same result? Is there a strong reason?
My friend – every reason shows the same result…test
this is a test preformed by siteground
Business scenario.
Updating bank info of a user in a table
– Allow when performed from Admin panel
– Restrict when performed from front end application/mobile app. In this case only allow updates when old value is null.