Home >Database >Mysql Tutorial >How to Unnest Comma-Separated Values in PostgreSQL and Preserve Element Order?
Expansion with element numbers in PostgreSQL
Question:
Using the unnest()
function to expand a column containing comma-separated values will only return the elements themselves, not their original positions in the string.
Target:
Get the element and its sequence number in the source string.
Solution:
Use string_to_table()
function and WITH ORDINALITY
clause:
<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>
Add WITH ORDINALITY
clause to unnest()
function:
<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>
Omit the row_number()
clause in the ORDER BY
function:
<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>
Create a custom function f_unnest_ord()
to extract elements and their 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>
Then use this to expand values with ordinal numbers:
<code class="language-sql">SELECT id, arr, (rec).* FROM (SELECT *, f_unnest_ord(arr) AS rec FROM (VALUES (1, '{a,b,c}'::text[])...) t) sub;</code>
The above is the detailed content of How to Unnest Comma-Separated Values in PostgreSQL and Preserve Element Order?. For more information, please follow other related articles on the PHP Chinese website!