MySQL - REVERSE() Function



The MySQL REVERSE() function accepts a string value as a parameter, rearranges the characters in it in reverse order, and returns the result.

This function can be useful in various scenarios such as reversing the order of a name, address or any other text string.

Syntax

Following is the syntax of MySQL REVERSE() function −

REVERSE(str)

Parameters

This function takes a string value as a parameter.

Return Value

This function returns the reversed version of the given string.

Example

In the following example, the function reverses the characters in the string 'Tutorialspoint' −

SELECT REVERSE('Tutorialspoint');

Following is the output of the above code −

REVERSE('Tutorialspoint')
tniopslairotuT

Example

If any of the arguments passed to the function is NULL, it returns NULL −

SELECT REVERSE(NULL);

The output obtained is as follows −

REVERSE(NULL)
NULL

Example

You can also pass numerical values as an argument to this function −

SELECT REVERSE(763275825171);

We get the output as follows −

REVERSE(763275825171)
171528572367

Example

You can also pass column name of a table as an argument to this function and rearrange the values in it in reverse order.

Let us create a table named "EMP" and insert records into it using CREATE and INSERT statements as shown below −

CREATE TABLE EMP(
   FIRST_NAME  CHAR(20) NOT NULL,
   LAST_NAME  CHAR(20),
   AGE INT,
   INCOME FLOAT
);

Now, let us insert records into it using the INSERT statement −

INSERT INTO EMP VALUES 
('Krishna', 'Sharma', 19, 2000),
('Raj', 'Kandukuri', 20, 7000),
('Ramya', 'Ramapriya', 25, 5000),
('Mac', 'Mohan', 26, 2000);

The EMP obtained is as follows −

FIRST_NAME LAST_NAME AGE INCOME
Krishna Sharma 19 2000
Raj Kandukuri 20 7000
Ramya Ramapriya 25 5000
Mac Mohan 26 2000

Following query rearranges the contents of the column "FIRST_NAME" in reverse order using the REVERSE() function −

SELECT FIRST_NAME, LAST_NAME, AGE, REVERSE(FIRST_NAME) as Result 
FROM EMP;

Output

After executing the above code, we get the following output −

FIRST_NAME LAST_NAME AGE Result
Krishna Sharma 19 anhsirK
Raj Kandukuri 20 jaR
Ramya Ramapriya 25 aymaR
Mac Mohan 26 caM
mysql-reverse-function.htm
Advertisements