SQL USER_NAME()

The USER_NAME() function in SQL Server is used to return the database username associated with the current session. It is commonly used for logging, auditing, and security-related tasks to determine which user is executing a query.

In this tutorial, we will explore the USER_NAME function, its syntax, and practical examples demonstrating its usage.


Syntax of SQL USER_NAME Function

The basic syntax of the USER_NAME() function is as follows:

</>
Copy
USER_NAME([id])

Parameters:

  • id (optional) – The ID of the user in the system catalog. If omitted, it returns the current user’s name.

Return Value: This function returns the username as a string.


Step-by-Step Examples Using SQL USER_NAME

1. Getting the Current Logged-in User

To retrieve the username of the currently connected user, use the following query:

</>
Copy
SELECT USER_NAME() AS user_name_1;

Explanation:

  • The USER_NAME() function returns the username of the session executing the query.
  • The alias user_name_1 is used to display the result in a readable format.

Example Output:


2. Retrieving the Username for a Specific User ID

To fetch the username associated with a specific user ID, use the following query:

</>
Copy
SELECT USER_NAME(1) AS username_for_id_1;

Explanation:

  • The function USER_NAME(1) returns the username associated with the user ID 1.
  • This is useful for mapping numeric user IDs to their actual usernames.

Example Output:

Similarly,


Conclusion

The USER_NAME() function is used to retrieve the username associated with the current session or a specific user ID. In this tutorial, we covered:

  1. How to get the current logged-in user.
  2. How to retrieve the username of a user by their ID.