How the RIGHT() Function Works in SQL Server (T-SQL)

In SQL Server, you can use the T-SQL RIGHT() function to return a given number of characters from the right part of a string.

The function accepts two arguments; the string itself, and the number of characters you’d like to be returned from that string.

Syntax

The official syntax for both functions goes like this:

RIGHT ( character_expression , integer_expression )

Where character_expression is the string, and integer_expression is the number of characters you want returned from that string.

If the second argument is type bigint and contains a large value, the first argument (i.e. the string) must be of a large data type such as varchar(max).

Example 1 – Basic Usage

Here’s an example of selecting the 3 rightmost characters from a string:

SELECT RIGHT('Coffee', 3) AS Result;

Result:

+----------+
| Result   |
|----------|
| fee      |
+----------+

Example 2 – Negative Integer Expression

The second argument must be a positive value. If it’s a negative value, an error is returned:

SELECT RIGHT('Coffee', -3) AS Result;

Result:

Invalid length parameter passed to the right function. 

Example 3 – Database Query

Here’s an example of using the RIGHT() function on data returned from a database:

USE Music;
SELECT TOP 7
    ArtistName AS Original, 
    RIGHT(ArtistName, 5) AS Modified
FROM Artists;

Result:

+------------------+------------+
| Original         | Modified   |
|------------------+------------|
| Iron Maiden      | aiden      |
| AC/DC            | AC/DC      |
| Allan Holdsworth | worth      |
| Buddy Rich       |  Rich      |
| Devin Townsend   | nsend      |
| Jim Reeves       | eeves      |
| Tom Jones        | Jones      |
+------------------+------------+