Skip to content

REVERSE String Function

The REVERSE string function returns the reverse of a string value. The syntax of the REVERSE string function is as follows:

REVERSE ( <string_expression> )

The <string_expression> parameter of the REVERSE string function is an expression of a string or binary data type which can be a constant, variable or column of either character or binary data. It must be of a data type that is implicitly convertible to VARCHAR data type.

Sample Uses of the REVERSE String Function

Here are a few examples of the uses of the REVERSE string function:

Usage #1 : Determine if a String is a Palindrome

DECLARE @Input VARCHAR(100) = 'NEVER ODD OR EVEN'

SELECT CASE WHEN REPLACE(@Input, ' ', '') = REVERSE(REPLACE(@Input, ' ', ''))
            THEN 'Palindrome'
            ELSE 'Not a Palindrome' END AS [IsPalindrome]
GO
IsPalindrome
-------------
Palindrome

Usage #2 : Get the Last Name from a Full Name

DECLARE @FullName VARCHAR(100) = 'Bill Gates'

SELECT REVERSE(LEFT(REVERSE(@FullName), CHARINDEX(' ', REVERSE(@FullName)) - 1)) AS [LastName]
SELECT RIGHT(@FullName, CHARINDEX(' ', REVERSE(@FullName)) - 1) AS [LastName]
LastName
----------
Gates

Usage #3 : Get the Page Name from a URL

DECLARE @URL VARCHAR(100) = 'http://www.database-helper.com/default.aspx'

SELECT REVERSE(LEFT(REVERSE(@URL), CHARINDEX('/', REVERSE(@URL)) - 1)) AS [PageName]
SELECT RIGHT(@URL, CHARINDEX('/', REVERSE(@URL)) - 1) AS [PageName]
PageName
-----------
default.aspx

Usage #4 : Get the File Name from a Full Path

DECLARE @FullFilePath VARCHAR(100)
SET @FullFilePath = 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Binn\sqlservr.exe'

SELECT REVERSE(LEFT(REVERSE(@FullFilePath), 
                    CHARINDEX('\', REVERSE(@FullFilePath)) - 1)) AS [FileName]
SELECT RIGHT(@FullFilePath, CHARINDEX('\', REVERSE(@FullFilePath)) - 1) AS [FileName]
FileName
----------
sqlservr.exe

Usage #5 : Get the Last Word from a Sentence / String

DECLARE @Sentence VARCHAR(100) = 'To be or not to be, that is the question'

SELECT REVERSE(LEFT(REVERSE(@Sentence), CHARINDEX(' ', REVERSE(@Sentence)) - 1)) AS [LastWord]
LastWord
----------
question