Little SQL Server Tricks: Get the Last 2 Letters in a Column

Getting parts of a string is usually a job for SUBSTRING. However, when you only care about the last two characters of a string, save yourself the troubles of calculating the starting point for the SUBSTRING function. A much simpler approach is to use the RIGHT function:

SELECT RIGHT('Hello world!', 2) -- returns d!

You can use this with a column name inside your SELECT statement as well:

SELECT [Name], RIGHT([Name], 2) AS 'ends with'
FROM [Sales].[Store]

Returns the last two characters

This RIGHT() function is lot simpler to remember than the calculation for SUBSTRING. Even better, you can use LEFT in the same way to get the first few characters of a string:

SELECT LEFT('Hello world!', 2) -- returns He

The next time you need a part form the beginning or the end of a string, use the RIGHT or LEFT function.