Get the Right Part of a String in SQL Server (T-SQL)

In SQL Server, you can use the RIGHT() function to extract the right part of a string.

It works exactly the same as the LEFT() function (which returns the left part of a string), except that it returns the right part of the string.

Example

Here’s an example to demonstrate.

SELECT RIGHT('Barney Rubble', 6);

Result:

Rubble

The first argument can be a constant, variable, or column. It can be of any data type, except text or ntext, that can be implicitly converted to varchar or nvarchar

If it can’t be implicitly converted to varchar or nvarchar, use CAST() or CONVERT() to convert it to a supported data type.

The function returns varchar if you pass in a non-Unicode character data type.

It returns nvarchar if you pass a Unicode character data type.

Database Column Example

Here’s an example of extracting the right part of a value returned in a database column.

SELECT TOP(10)
  name,
  RIGHT(name, 5) AS [Right Part]
FROM sys.objects;

Result:

+----------------+--------------+
 | name           | Right Part   |
 |----------------+--------------|
 | sysrscols      | scols        |
 | sysrowsets     | wsets        |
 | sysclones      | lones        |
 | sysallocunits  | units        |
 | sysfiles1      | iles1        |
 | sysseobjvalues | alues        |
 | sysmatrixages  | xages        |
 | syspriorities  | ities        |
 | sysdbfrag      | bfrag        |
 | sysfgfrag      | gfrag        |
 +----------------+--------------+