Reverse a string.
MySQL REVERSE() Function
Summary: in this tutorial, you will learn how to use the MySQL REVERSE() function to reverse the characters within a string.
Introduction to MySQL REVERSE() function
The REVERSE() function accepts a string and returns a new string with the order of characters reversed.
Here’s the basic syntax of the REVERSE() function:
REVERSE(string)Code language: SQL (Structured Query Language) (sql)In this syntax:
string: The input string that you want to reverse.
The REVERSE() function returns the string with the order of the characters reversed. If the string is NULL, the REVERSE() function returns NULL.
MySQL REVERSE() function examples
Let’s take some examples of using the REVERSE() function.
1) Simple REVERSE() function example
The following example uses the REVERSE() function to reverse the string "ABC":
SELECT REVERSE('ABC');Code language: SQL (Structured Query Language) (sql)Output:
+----------------+
| REVERSE('ABC') |
+----------------+
| CBA |
+----------------+
1 row in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)2) Using the REVERSE() function with table data
We’ll use the employees table from the sample database:
The following example uses the REVERSE() function to reverse the first names of employees:
SELECT
firstName,
reverse(firstName)
FROM
employees;Code language: SQL (Structured Query Language) (sql)Output:
+-----------+--------------------+
| firstName | reverse(firstName) |
+-----------+--------------------+
| Diane | enaiD |
| Mary | yraM |
| Jeff | ffeJ |
| William | mailliW |
| Gerard | drareG |
| Anthony | ynohtnA |
...Code language: SQL (Structured Query Language) (sql)3) Using REVERSE() function to detect palindromes
A palindrome is a string that reads the same forward and backward. For example, "level" is a palindrome.
To check if a string is a palindrome, you use the REVERSE() function to reverse it and compare the reversed string with the original string.
First, create a new table that stores the words:
CREATE TABLE words(
id INT AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(255) NOT NULL
);Code language: SQL (Structured Query Language) (sql)Second, insert some rows into the words table:
INSERT INTO words(word)
VALUES('radar'), ('level'),('deified'),('man'),('12321');Code language: SQL (Structured Query Language) (sql)Third, use the REVERSE() function to check if a value in the word column is a palindrome:
SELECT
word,
REVERSE(word),
(
word = REVERSE(word)
) palindrome
FROM
words;Code language: SQL (Structured Query Language) (sql)Output:
+---------+---------------+------------+
| word | REVERSE(word) | palindrome |
+---------+---------------+------------+
| radar | radar | 1 |
| level | level | 1 |
| deified | deified | 1 |
| man | nam | 0 |
| 12321 | 12321 | 1 |
+---------+---------------+------------+Code language: SQL (Structured Query Language) (sql)Summary
- Use the
REVERSE()function to reverse characters in a string.