Reverse a text in PostgreSQL Posted by Andreas 'ads' Scherbaum on Monday, July 24. 2006 I'm always searching for a reverse function, so here is the link:http://www.varlena.com/GeneralBits/53.phpcode snippet is available in plperl and plpgsql. Trackbacks Trackback specific URI for this entry No Trackbacks Comments Display comments as Linear | Threaded dys on Friday, July 28. 2006: Using recursion, one can also achieve it with a plain sql function: create function reverse(text) returns text as $$ select case when length($1)>0 then substring($1, length($1), 1) || reverse(substring($1, 1, length($1)-1)) else '' end $$ language sql immutable strict;Comments () Pavel Stehule on Wednesday, July 27. 2011: a code from Varlena is not good - there is a few issues - first issue is using a WHILE statement. FOR statement is better - is faster. And you can use a simple and relative fast SQL function create or replace function rvrs(text) returns text as $$ select string_agg(substring($1 from i for 1),'') from generate_series(length($1),1,-1) g(i) $$ language sql;Comments () Alexandr on Saturday, September 24. 2011: Here is one more function to reverse text that uses FOR statement if anybody interested. create or replace function rev(varchar) returns varchar as $$ declare _temp varchar; _count int; begin _temp := ''; for _count in reverse length($1)..1 loop _temp := _temp || substring($1 from _count for 1); end loop; return _temp; end; $$ language plpgsql immutable;Comments () Add Comment Name* Email* Homepage Comment* In reply to [ Top level ]#1: dys on 2006-07-28 21:20 #2: Pavel Stehule on 2011-07-27 20:36 #3: Alexandr on 2011-09-24 19:42 Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.E-Mail addresses will not be displayed and will only be used for E-Mail notifications.To leave a comment you must approve it via e-mail, which will be sent to your address after submission. Form options Remember Information?