Skip to content

Reverse a text in PostgreSQL

I'm always searching for a reverse function, so here is the link:

code snippet is available in plperl and plpgsql.


No Trackbacks


Display comments as Linear | Threaded

dys on :

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 :

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 :

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

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