Published on

October 14, 2021

Understanding the SQL RIGHT Function

In this article, we will explore the SQL RIGHT function and its usage in SQL Server. The RIGHT function is a built-in string function that allows us to extract the right part of a character string based on the specified number of characters.

Syntax

The syntax for the RIGHT function is as follows:

RIGHT(string, number_of_characters)

Arguments

The RIGHT function takes two arguments:

  • string: The string expression from which we want to extract the right part.
  • number_of_characters: The number of characters to be extracted from the right side of the string.

Return Type

The return type of the RIGHT function is varchar when the string parameter is a non-Unicode character data type. The return type is nvarchar when the string parameter is a Unicode character data type.

Examples

Let’s look at some examples to understand how to use the RIGHT function:

Example 1: Extracting the Right Part of a String

SELECT RIGHT('Hello World', 5) AS Result;

This query will return the rightmost 5 characters of the string ‘Hello World’, which is ‘World’.

Example 2: Using the RIGHT Function with a Table Column

SELECT LastName, RIGHT(LastName, 3) AS Nickname
FROM Employees;

This query will return the last 3 characters of the LastName column for each row in the Employees table.

Example 3: Using the RIGHT Function with Variables

DECLARE @txt VARCHAR(100);
SET @txt = 'Hello World';
SELECT RIGHT(@txt, 5) AS Result;

This query will extract the rightmost 5 characters from the value stored in the @txt variable.

Performance Considerations

When using the RIGHT function in a query, it’s important to consider its impact on query performance. Similar to the LEFT function, using the RIGHT function in the WHERE clause can lead to inefficient query plans and excessive resource consumption.

To optimize performance, it is recommended to avoid using the RIGHT function directly in the WHERE clause. Instead, consider using other operators like LIKE or SUBSTRING to achieve the desired result.

Conclusion

The SQL RIGHT function is a useful tool for extracting the right part of a string in SQL Server. By understanding its syntax and usage, you can effectively manipulate character data in your queries. However, it’s important to be mindful of its impact on query performance and consider alternative approaches when necessary.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.