PostgreSQL REVERSE() Function
Summary: in this tutorial, you will learn how to use the PostgreSQLREVERSE()
function to reverse the characters within a string.
Introduction to PostgreSQL REVERSE() function
TheREVERSE()
function accepts a string and returns a new string with the order of all characters reversed.
Here’s the syntax of theREVERSE()
function:
REVERSE(text)
In this syntax:
text
: The input string that you want to reverse.
TheREVERSE()
function returns a string with the order of all the characters reversed.
TheREVERSE()
function returnsNULL
if thetext
isNULL
.
MySQL REVERSE() function examples
Let’s explore some examples of using theREVERSE()
function.
1) Basic PostgreSQL REVERSE() function example
The following example uses theREVERSE()
function to reverse the string"SQL"
:
SELECT REVERSE('SQL');
Output:
reverse--------- LQS(1 row)
2) Using the PostgreSQL REVERSE() function with table data
We’ll use thecustomer
table from thesample database:
The following example uses the
REVERSE()
function to reverse the first names of customers:
SELECT first_name, REVERSE(first_name)FROM customerORDER BY first_name;
Output:
first_name | reverse-------------+------------- Aaron | noraA Adam | madA Adrian | nairdA Agnes | sengA
3) Using REVERSE() function to detect palindromes
A palindrome is a string that reads the same forward and backward such as"radar"
.
You can use theREVERSE()
function to reverse a string and then compare the reversed string with the original string to determine if it is a palindrome. For example:
First,create a new table calledwords
to store the words:
CREATE TABLE words( idSERIAL PRIMARY KEY, wordVARCHAR(255)NOT NULL);
Second,insert some rows into thewords
table:
INSERT INTO words(word)VALUES('radar'), ('level'),('civic'),('man'),('12321'),('madam')RETURNING*;
Output:
id | word----+------- 1 | radar 2 | level 3 | civic 4 | man 5 | 12321 6 | madam(6 rows)
Third, determine if a value in theword
column is a palindrome using theREVERSE()
function:
SELECT word, REVERSE(word), ( word = REVERSE(word) )palindromeFROM words;
Output:
word | reverse | palindrome-------+---------+------------ radar | radar | t level | level | t civic | civic | t man | nam | f 12321 | 12321 | t madam | madam | t(6 rows)
Summary
- Use the PostgreSQL
REVERSE()
function to reverse the order of characters within a string.
Last updated on