A wide range of built-in string functions is available in PostgreSQL that allows us to manipulate the text data. The “REVERSE()” is one of the string functions that is used to reverse the sequence of the string characters. The REVERSE() function accepts one of the string data types like TEXT, VARCHAR, etc., and its return type is text. A common use case of the REVERSE() function is to check if a specific string is a palindrome or not.
This article presents a detailed guide on how to reverse a string in Postgres using the REVERSE() function.
How to Use the REVERSE() Function in Postgres?
The REVERSE() function accepts exactly one argument and that must be a string. As a result, it retrieves the given string in reverse order. Here is the basic syntax:
REVERSE(str);
The “str” can be of TEXT, CHAR, or VARCHAR data type.
Example 1: Reversing a String Using REVERSE() Function
In the following example, a string is passed to the REVERSE() function:
SELECT REVERSE('Hello Welcome to USA');
The given string has been reversed successfully.
Example 2: Using REVERSE() Function With Table’s Data
We will use the “employee_information” table that has been already created in the database:
SELECT * FROM employee_information;
Let’s utilize the REVERSE() function to reverse the data of “e_email” column:
SELECT *, REVERSE(e_email) FROM employee_information;
The result shows that the “REVERSE()” function successfully changes the order of the given string data.
Example 3: Using REVERSE() Function in PL/pgSQL
The following example illustrates how to check if a string is a palindrome or not:
DO $$ DECLARE name TEXT := 'bob'; reverse_name TEXT := REVERSE(name); BEGIN IF name = reverse_name THEN RAISE NOTICE 'Palindrome'; ELSE RAISE NOTICE 'Not Palindrome'; END IF; END $$;
In the above example,
- Two string variables are declared.
- The first variable is assigned a string value, while the second variable is initialized with the reverse of the first variable.
- The if-else statement is used to check if the given string is a palindrome or not.
The output shows that the given string is a palindrome.
Conclusion
The “REVERSE()” is one of the string functions that is used to reverse the sequence of a string. The REVERSE() function accepts exactly one argument and that must be a string. As a result, it retrieves the given string in reverse order. The accepted argument can be of TEXT, CHAR, or VARCHAR data type. This post has explained various use cases of the Postgres REVERSE() function.