Using REVERSE String Function in PostgreSQL

Updated: January 6, 2024 By: Guest Contributor Post a comment

Overview

The REVERSE string function in PostgreSQL is quite a straightforward but incredibly useful string manipulation tool. This function, designed to reverse the order of the characters in a given string, has been a staple in SQL databases for years. It finds use cases in a variety of scenarios including but not limited to data sanitization, data encryption/decryption stubs, palindromic checks, and more.

Uses

The REVERSE function’s primary purpose is to invert the order of characters in a string. This means the last character becomes the first, the second-to-last becomes the second, and so on, until the string is completely reversed.

Syntax and Parameters

The syntax for the REVERSE function in PostgreSQL is quite simple:

REVERSE(string)

Where string is the string value you want to reverse. It can be any expression that resolves to a text.

The function returns the reversed string. For example, REVERSE(‘PostgreSQL’) would return ‘LQSgtsoP’.

Code Examples

Basic String Reversal

Let us start with the most basic example – reversing a literal string.

SELECT REVERSE('Hello, World!');

The output of the above query will be '!dlroW ,olleH'.

Reversing Table Column Data

In this example, we’ll reverse the contents of a column for each row in a table.

CREATE TABLE example (
    id SERIAL PRIMARY KEY,
    content TEXT NOT NULL
);

INSERT INTO example (content) VALUES
('First'),
('Second'),
('Third');

SELECT id, REVERSE(content) AS reversed_content FROM example;

This will return the reversed version of each string in the content column alongside the id.

Conditional String Reversion

Here, we’ll reverse strings only when they match certain criteria.

SELECT id, 
       content, 
       CASE WHEN content = 'Second' THEN REVERSE(content) ELSE content END AS modified_content
FROM example;

This query will reverse the content only where the original content equals ‘Second’.

Conclusion

The REVERSE string function is an elegant and simple utility in PostgreSQL for string manipulation. While it may not be something that you use every day, it can be incredibly handy for specific tasks that involve reversing string sequences. It’s easy to use, and as part of the SQL standards, it can be adopted into routine operations with minimal learning curve.