MySQL REVERSE() Function

The REVERSE() function in MySQL is used to reverse the characters of a string and return the reversed string.


Syntax

REVERSE(string)

Parameters

Parameter Description
string Required. The string that you want to reverse.

Definition and Usage

  • The REVERSE() function reverses the characters in a string.
  • It returns the string with its characters in the opposite order.

Usage Examples

Example 1: Reversing a Simple String

Reverse the string "SQL Tutorial":

SELECT REVERSE("SQL Tutorial");

Output:

REVERSE("SQL Tutorial")
lairotuT LQS

Explanation: The string "SQL Tutorial" is reversed, and the result is "lairotuT LQS".


Example 2: Reversing the Text in a Column

Reverse the text in the CustomerName column of the Customers table:

SELECT REVERSE(CustomerName)
FROM Customers;

Output:

REVERSE(CustomerName)
emahS
nnaB
uoS

Explanation: The function reverses the CustomerName for each row in the Customers table.


Technical Details

  • Works In: From MySQL 4.0 onwards.
  • Return Type: The function returns a string with the characters reversed.
  • Behavior: It works for all types of strings (including special characters, spaces, and numbers).

Applications

  1. Text Manipulation: Useful when you need to reverse strings for display or processing purposes.
  2. Data Transformation: You may need to reverse strings for certain encoding or data formats.
  3. Reversal for Matching: Reversing strings can be part of algorithms for pattern matching or cryptography.

Example Use Case

If you are storing user-generated usernames in the database and you want to create a reversed version for some encoding or logging purposes, you can use the REVERSE() function:

UPDATE Users
SET ReversedUsername = REVERSE(Username);

This would store the reversed version of each user's username in the ReversedUsername column.


Key Notes

  • The REVERSE() function is simple to use but can be helpful in scenarios that involve string processing or data manipulation.
  • It works with any character set supported by MySQL, and the reversed string will respect the character set’s encoding.

The REVERSE() function can be a handy tool when manipulating strings, especially for tasks involving transformations or generating reversed versions of data.


Was this article helpful?