The REVERSE() function in SQL is used to reverse the given string. The REVERSE() function reverses a string and returns the result.
SQL REVERSE
SQL REVERSE() function is used for reversing the string. It accepts a string of characters as an argument and returns the reverse order of the string. The REVERSE is one of the SQL String Functions used to reverse the specified expression.
See the following syntax of the REVERSE function.
Syntax
SELECT REVERSE(string)
Parameters
String: The source string of which characters have to be reversed.
Note
The string expression must be of a data type that can be implicitly converted to VARCHAR. Otherwise, CAST has to be used explicitly for converting to VARCHAR.
Example
See the following query.
SELECT REVERSE ('AppDividend.com');
Output
moc.dendiviDppA
Query 2
SELECT REVERSE ('edcba');
Output
abcde
Query 3
SELECT REVERSE (' SQL');
Output
LQS
Query 4
SELECT REVERSE ('123');
Output
321
Above are the common examples to make clear how this function work. Next, let’s apply this function to a TABLE.
Table: Employee
Emp_id | First_name | City | State | Phone |
101 | Rohit | Patna | Bihar | 8585145852 |
201 | Shivam | Jalandhar | Punjab | 8958458785 |
301 | Karan | Allahabad | Uttar Pradesh | 9987845784 |
401 | Suraj | Kolkata | West Bengal | 88789898980 |
501 | Akash | Vizag | Andhra Pradesh | 98985475001 |
Suppose we want to reverse the first_name of the employee, then the following query has to be considered.
Query
Select First_name, REVERSE (First_name) AS Reversed_Name from Employee;
Output
First_name | Reversed_Name |
Rohit | tihoR |
Shivam | mavihS |
Karan | naraK |
Suraj | jaruS |
Akash | hsakA |
Here, you can see that the First_name of the employee has been reversed.
SQL SERVER Reverse Function
Let’s use the SQL SERVER REVERSE function to check whether a string is a palindrome.
A palindrome string is a string whose original and reversed strings are equal.
EX: MaM, DaD
Query
DECLARE @input VARCHAR (100) = 'MadaM'; SELECT CASE WHEN @input = REVERSE(@input) THEN 'Palindrome' ELSE 'Not Palindrome' END result;
Output
Palindrome
Explanation
Here, the above string MadaM, which was given as input, was a palindrome.
MySQL REVERSE() Function
MySQL REVERSE() function reverses a string and returns the result.
It works from MySQL 4.0.
That’s it for this tutorial.