Lesson

MySQL USER() Function

10 min reading
Free Course

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 returns NULL during 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() vs CURRENT_USER(): If you log in as dev@10.0.0.5 and match a wildcard grant dev@%, USER() returns 'dev@10.0.0.5' whereas CURRENT_USER() returns 'dev@%'.
  • Empty username on anonymous grants: If MySQL authenticates an anonymous user, USER() may still show what the client sent ('@localhost'), while CURRENT_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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum