1
0
mirror of https://github.com/postgres/postgres.git synced 2025-09-02 04:21:28 +03:00

Support negative indexes in split_part().

This provides a handy way to get, say, the last field of the string.
Use of a negative index in this way has precedent in the nearby
left() and right() functions.

The implementation scans the string twice when N < -1, but it seems
likely that N = -1 will be the huge majority of actual use cases,
so I'm not really excited about adding complexity to avoid that.

Nikhil Benesch, reviewed by Jacob Champion; cosmetic tweakage by me

Discussion: https://postgr.es/m/cbb7f861-6162-3a51-9823-97bc3aa0b638@gmail.com
This commit is contained in:
Tom Lane
2020-11-13 13:49:48 -05:00
parent 3bf44303b9
commit ec0294fb2c
4 changed files with 172 additions and 17 deletions

View File

@@ -3356,11 +3356,17 @@ repeat('Pg', 4) <returnvalue>PgPgPgPg</returnvalue>
<para>
Splits <parameter>string</parameter> at occurrences
of <parameter>delimiter</parameter> and returns
the <parameter>n</parameter>'th field (counting from one).
the <parameter>n</parameter>'th field (counting from one),
or when <parameter>n</parameter> is negative, returns
the |<parameter>n</parameter>|'th-from-last field.
</para>
<para>
<literal>split_part('abc~@~def~@~ghi', '~@~', 2)</literal>
<returnvalue>def</returnvalue>
</para>
<para>
<literal>split_part('abc,def,ghi,jkl', ',', -2)</literal>
<returnvalue>ghi</returnvalue>
</para></entry>
</row>