Given a string column that represents a path ('/11/22/33/44'), how do I return the next number after the given one.
For example:
- given an id=
22, I want to return33from the path/11/22/33/44/. - given an id=
44, I want to returnNULLfrom the path/11/22/33/44/.
This is the bit I use to convert the string into a set of records:
SELECT unnest(string_to_array(trim(both '/' from '/11/22/33/44/'), '/')::integer[]);
unnest
--------
11
22
33
44
(4 rows)
But how to obtain the “next entry” here (so given 22 -> 33)?
One way is a window function:
This solution returns zero rows for the
44input, but that’s easily addressed by invoking it as a subquery.Alternately, for integer arrays you can use the intarray extension‘s
idxfunction:to look up the next index in the array.
intarrayis an extension distributed with PostgreSQL, it’s not a 3rd party add-on. This solution produces aNULLresult for44without further manipulation.