SQL Server RIGHT Function

Summary: in this tutorial, you will learn how to use the SQL Server RIGHT() function to extract a number of character from the right side of a given character string.

SQL Server RIGHT() function overview

The RIGHT() function extracts a given number of characters from the right side of a specified character string. For example, RIGHT('SQL Server', 6) returns Server.

The syntax of the RIGHT() function is as follows:

RIGHT ( input_string , number_of_characters )  
Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • The input_string can be a literal string, variable, or column. The result of the input_string can be in any data type, except for TEXT or NTEXT, that is implicitly converted to VARCHAR or NVARCHAR.
  • The number_of_characters is a positive integer that specifies the number of characters of the input_string will be returned.

Note that the RIGHT() function returns a value of VARCHAR when the input_string is a non-Unicode character data type or NVARCHAR if the input_string is a Unicode character data type.

SQL Server RIGHT() function examples

The following statement uses RIGHT() to return the three rightmost characters of the character string SQL Server:

SELECT RIGHT('SQL Server',6) Result_string;
Code language: SQL (Structured Query Language) (sql)

Here is the output:

Result_string
-------------
Server

(1 row affected)

The following example returns the four rightmost characters of each product name in the production.products table from the sample database:

SELECT 
    product_name,
    RIGHT(product_name, 4) last_4_characters
FROM 
    production.products
ORDER BY 
    product_name;
Code language: SQL (Structured Query Language) (sql)

Here is the partial output:

SQL Server RIGHT Function Example

In this tutorial, you have learned how to use the SQL Server RIGHT() function to get the right part of a character string with the specified number of characters.

Was this tutorial helpful?