For comma separated strings, use the string_to_table()
function instead of unnest(string_to_array())
:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl t LEFT JOIN LATERAL string_to_table(t.elements, ',') WITH ORDINALITY AS a(elem, nr) ON true;</code>
Append WITH ORDINALITY
for functions that return collections:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl AS t LEFT JOIN LATERAL unnest(string_to_array(t.elements, ',')) WITH ORDINALITY AS a(elem, nr) ON true;</code>
Use row_number() OVER (PARTITION BY id)
(without ORDER BY
) to get the serial number:
<code class="language-sql">SELECT *, row_number() OVER (PARTITION by id) AS nr FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;</code>
Implement custom function f_unnest_ord()
for splitting elements with serial numbers:
<code class="language-sql">CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer) RETURNS SETOF record LANGUAGE sql IMMUTABLE AS 'SELECT [i], i - array_lower(,1) + 1 FROM generate_series(array_lower(,1), array_upper(,1)) i';</code>
The above is the detailed content of How to Efficiently Unnest Comma-Separated Strings in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!