SQL Server REVERSE Function


By:

The REVERSE function is used to provide the string characters in the reverse order.

Syntax

REVERSE(expression)

Parameters

  • expression - this is a string, number, binary data or expression to be reversed.

Simple REVERSE Example

Below is a simple example of using REVERSE function to reverse the word ROME.

SELECT REVERSE('ROME') as msg 
simple reverse example

REVERSE Example Using a Table

The following example will reverse the FirstName from the Person table.

SELECT FirstName, REVERSE(FirstName) as reversename
FROM [Person].[Person]
t-sql reverse function with tables

REVERSE Example with Numbers

The following example will reverse the numbers.

SELECT REVERSE(12345) as msg 
reverse numbers in sql server

REVERSE with NULL values

If the parameter is NULL the value returned by the function will be null as well.

SELECT REVERSE(null) as msg 
REVERSE function with NULL values

RVEVERSE Function with RIGHT and CHARINDEX

In this example, we want to get the text after the colon. We will get the position of the colon counting from the right using the reverse function and then we will use the RIGHT function to get the text to the right of the colon.

DECLARE @string nvarchar(20) = 'Example:New'

DECLARE @position int = CHARINDEX(':',REVERSE(@string))-1

SELECT RIGHT(@string, @position) output
get substring using reverse and charindex

Related Articles


Last Update: 11/10/2021




Comments For This Article

















get free sql tips
agree to terms