A Quick Look at PostgreSQL’s REVERSE() Function

In PostgreSQL, we can use the reverse() function to return a specified string with its characters reversed. In other words, the string is returned with its characters in the reverse order to how we provided them.

Example

Here’s an example to demonstrate:

SELECT reverse('desserts');

Result:

stressed

So we can see that the first character has been moved so that it’s the last character, the second character is now the second last character, and so on.

Uppercase vs Lowercase

The reverse() function doesn’t try to make any meaning out of its results – it simply reverses the order of the characters. So we can’t expect it to change the case of the letters for example, when the result is a new word.

Here’s an example of what I mean:

SELECT reverse('Desserts');

Result:

stresseD

So we can see that the uppercase D was simply moved to the end, and it remains uppercase. The reverse() function didn’t decide that it should now be lowercase merely because it has been moved to the end of the sentence. The same applies to the s character from the end of the original string. It doesn’t automatically become an uppercase S on the basis that it is now at the start of the sentence.

We do have the option of using functions like upper(), lower(), and initcap() to convert the whole string to uppercase or lowercase, or initial caps if required:

SELECT 
    initcap(reverse('Desserts')) AS "initcap",
    upper(reverse('Desserts')) AS "upper",
    lower(reverse('Desserts')) AS "lower";

Result:

 initcap  |  upper   |  lower   
----------+----------+----------
Stressed | STRESSED | stressed

Bear in mind that these functions apply to all characters/words in the string:

SELECT 
    initcap(reverse('Mad Desserts')) AS "initcap",
    upper(reverse('Mad Desserts')) AS "upper",
    lower(reverse('Mad Desserts')) AS "lower";

Result:

   initcap    |    upper     |    lower     
--------------+--------------+--------------
Stressed Dam | STRESSED DAM | stressed dam