MySQL USER() Function
MySQL USER() Function
The MySQL USER() function returns the current MySQL username and client hostname that the client specified when connecting to the server. It always uses the format 'username@hostname'.
Syntax
USER()
- Takes zero arguments and returns a string (
VARCHAR).
USER() is the primary MySQL function for identifying the connecting client; SESSION_USER() and SYSTEM_USER() are aliases for it.
Practical Example
Suppose you want both the full user@host string and only the bare username (before @) for an audit table tied to demo_orders. Combine USER() with SUBSTRING_INDEX().
SELECT
USER() AS full_client_user,
SUBSTRING_INDEX(USER(), '@', 1) AS username_only,
SUBSTRING_INDEX(USER(), '@', -1) AS client_host;
| full_client_user | username_only | client_host |
|---|---|---|
| reporting_svc@10.2.0.15 | reporting_svc | 10.2.0.15 |
Common Mistakes & NULL Behavior
- NULL behavior:
USER()accepts zero arguments and never returnsNULLduring an active connection. Passing any parameter raises a syntax error. - Proxy or Unix socket hosts: Local CLI connections over a socket report
root@localhost, while Docker or TCP connections report the container or proxy IP (user@172.18.0.4). USER()vsCURRENT_USER(): If you log in asdev@10.0.0.5and match a wildcard grantdev@%,USER()returns'dev@10.0.0.5'whereasCURRENT_USER()returns'dev@%'.- Empty username on anonymous grants: If MySQL authenticates an anonymous user,
USER()may still show what the client sent ('@localhost'), whileCURRENT_USER()shows''@'localhost'.
Frequently Asked Questions
How do I get just the username without @host in MySQL?
Use SUBSTRING_INDEX(USER(), '@', 1) to extract everything before the @ symbol.
Does USER() return the same value inside stored procedures?
Yes. USER() always returns the original connected client's user@host, even inside SQL SECURITY DEFINER stored procedures and views.
Are parentheses mandatory for USER()?
Yes. Always write USER() with parentheses; SELECT USER fails because USER without parentheses is not a built-in keyword alias.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.