SQL Server USER_NAME() Function

The USER_NAME() function in SQL Server retrieves the name of a database user. You can either specify a user ID to get that user's name, or omit the ID to get the name of the currently connected user.



USER_NAME(): Definition and Usage

This function is helpful for identifying users, particularly in security-related tasks or auditing processes. Knowing the current user is essential for many applications.

Syntax

Syntax

USER_NAME(id_number)
      

Parameter Values

Parameter Description
id_number (Optional) The ID of the database user. If omitted, it returns the name of the currently connected user.

Examples

Getting the Current User's Name

This example retrieves the name of the currently logged-in user.

Syntax

SELECT USER_NAME();
      
Output

YourUserNameHere (Replace with your actual username)
      

Getting a User's Name by ID

This example retrieves the user name associated with ID 1 (assuming user with ID 1 exists).

Syntax

SELECT USER_NAME(1);
      
Output

User1Name (Replace with the actual name of the user with ID 1)
      

Technical Details

The USER_NAME() function is available in:

  • SQL Server (starting with version 2008)
  • Azure SQL Database
  • Azure SQL Data Warehouse
  • Parallel Data Warehouse