SQL Server REVERSE Function

Summary: in this tutorial, you will learn how to use the SQL Server REVERSE() function to return the reverse order of a string.

SQL Server REVERSE() function overview #

The REVERSE() function accepts a string argument and returns the reverse order of that string.

The following shows the syntax of the REVERSE() function.

REVERSE ( input_string )  
Code language: SQL (Structured Query Language) (sql)

The input_string is a character string expression. Otherwise, you must use CAST to explicitly convert the input string to VARCHAR.

SQL Server REVERSE() function examples #

Let’s take some examples of using the REVERSE() function

A) Using SQL Server REVERSE() function to reverse a string #

SQL Server REVERSE() Function

This example uses the REVERSE() function to reverse the string 'ecnalubma':

SELECT 
    REVERSE('ecnalubma') result;
Code language: SQL (Structured Query Language) (sql)

The output is as follows:

result
---------
ambulance

(1 row affected)

B) Using SQL Server REVERSE() function to determine if a string is a palindrome #

A palindrome is a word that reads the same backward as forwarding e.g., madam or redivider. The following example uses the REVERSE() function and CASE expression to check if a string is a palindrome.

DECLARE 
    @input VARCHAR(100) = 'redivider';

SELECT 
    CASE
        WHEN @input = REVERSE(@input)
        THEN 'Palindrome'
        ELSE 'Not Palindrome'
    END result;
Code language: SQL (Structured Query Language) (sql)

Here is the result:

result
--------------
Palindrome

(1 row affected)

In this tutorial, you have learned how to use the SQL Server REVERSE() function to return a reverse order of a string.

Was this tutorial helpful?