Waiting for PostgreSQL 18 – Add SQL function array_reverse()

On 1st of November 2024, Michael Paquier committed patch:

Add SQL function array_reverse()
 
This function takes in input an array, and reverses the position of all
its elements.  This operation only affects the first dimension of the
array, like array_shuffle().
 
The implementation structure is inspired by array_shuffle(), with a
subroutine called array_reverse_n() that may come in handy in the
future, should more functions able to reverse portions of arrays be
introduced.
 
Bump catalog version.
 
Author: Aleksander Alekseev
Reviewed-by: Ashutosh Bapat, Tom Lane, Vladlen Popolitov
Discussion: https://postgr.es/m/CAJ7c6TMpeO_ke+QGOaAx9xdJuxa7r=49-anMh3G5476e3CX1CA@mail.gmail.com

The change seems simple enough, but let's see how that works:

$ SELECT array_agg(datname ORDER BY oid) FROM pg_database ;
                            array_agg
──────────────────────────────────────────────────────────────────
 {template1,template0,postgres,depesz_explain,pgdoc,depesz,pgdba}
(1 ROW)
 
$ SELECT array_reverse( array_agg(datname ORDER BY oid) ) FROM pg_database ;
                          array_reverse
──────────────────────────────────────────────────────────────────
 {pgdba,depesz,pgdoc,depesz_explain,postgres,template0,template1}
(1 ROW)

Of course in this example I could have just as easily change order by clause in the aggregate, but the point still stands – we now have a way to reverse array without building one-liner sql custom function 🙂

I do like that we get more features like this, would love to see more extensions to arrays support, so while not huge, it's definitely a step in the right direction.

Thanks to everyone involved.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.