Development

SQL Server Right Function

Captain Salem 1 min read

SQL Server Right Function

Ever wanted to quickly grasp the tail end of a string in SQL Server? Whether it’s extracting the last few digits of a phone number or capturing file extensions, the RIGHT() function is an invaluable tool in your SQL toolbox.

In this tutorial, we will explore how to use the right() function in SQL Server to retrieve specific characters from the end of an input string in an efficient manner.

SQL Server Right() Function

The following shows the syntax of the right() function in SQL Server:

RIGHT ( character_expression , integer_expression )

Function Parameters

The function parameters are expressed as shown:

  • character_expression - specifies an expression of characters or binary data. This can be a constant, a variable, or a column.
If string_expression is of type binary or varbinary, RIGHT will perform an implicit conversion to varchar, and therefore will not preserve the binary input.
  • integer_expression - specifies a positive integer determining the number of characters to be returned from the specified character_expression.

Function Return Values

The functon returns varchar is the specified character_expression is a non-Unicode character data type. if the input is Unicode character type, the function returns an nvarchar data type.

Examples

Example 1 - Using the Right Function with a Character String

The following example demonstrates how to use the right() function with a character string.

SELECT RIGHT('Hello World!', 2);

Output:

-------  
d!

Example 2 - Using the Right Function with a Column

Assuming we have a table named Employees with a column EmployeeID and we want to get the last 4 characters/digits of each EmployeeID:

SELECT EmployeeID, 
       RIGHT(EmployeeID, 4) AS LastFourChars 
FROM Employees;
----------  
Keni
Teri 
bert
Roby

Conclusion

In this tutorial, we learned how to use the SQL Server right() function to extract a specified number of characters from the right of an input string.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.