String operation in SQL to reverse a string

Joe Platano picture Joe Platano · Nov 27, 2014 · Viewed 8.4k times · Source

In DB2 9.7 I am looking for a way to reverse a string in a SQL query.

I am familiar with SQL Server where the query would be like

SELECT
    REVERSE(LEFT_TO_REIGHT) AS RIGHT_TO_LEFT
FROM 
    TABLE1;

I couldn't find a similar function in DB2. is there a simple way to reverse a string?

Answer

Clockwork-Muse picture Clockwork-Muse · Nov 29, 2014

Creating a REVERSE(..) function is unnecessary.
DB2 has something called RIGHT(string-expression, length):

The RIGHT function returns the rightmost string of string-expression of length length, expressed in the specified string unit. If string-expression is a character string, the result is a character string. If string-expression is a graphic string, the result is a graphic string

So if you're interested in the last 8 characters, you can pretty trivially do this via:

SELECT RIGHT(left_to_right, 8) AS right_to_left
FROM Table1

(I'm actually still concerned about the fact that you're splitting off 8 characters consistently, as it implies you have a multi-part key of some sort).