MySQL USER() Explained

In MySQL, USER() is a built-in function that returns the current MySQL user name and host name, given when connecting to MySQL.

The result is returned as a string in the utf8mb3 character set.

The value returned by USER() could be different to the value returned by CURRENT_USER().

Syntax

The syntax goes like this:

USER()

No arguments are required or accepted.

Example

Here’s an example to demonstrate:

SELECT USER();

Result:

+------------------+
| USER()           |
+------------------+
| barney@localhost |
+------------------+

USER() vs CURRENT_USER()

The USER() function doesn’t always return the same result as the CURRENT_USER() function.

For example, if we connect using an anonymous user:

mysql

Then run USER() and CURRENT_USER():

SELECT 
    USER(),
    CURRENT_USER;

Result:

+------------------+--------------+
| USER()           | CURRENT_USER |
+------------------+--------------+
| barney@localhost | @localhost   |
+------------------+--------------+

Here, the client specified a user name of barney, but the server authenticated the client using an anonymous user account. Therefore the USER() function returns barney, and CURRENT_USER() returns @localhost.

No Arguments are Accepted

The USER() function doesn’t accept any arguments. Passing any arguments to USER() results in an error:

SELECT USER(123);

Result:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123)' at line 1

The SESSION_USER() and SYSTEM_USER() Functions

MySQL has a SESSION_USER() function and a SYSTEM_USER() function that are both synonyms for USER(). Any of the examples above can be done with all three functions.