1

I have an array column I want to unnest, split the element values, and copy into another table. For example:

id | col1
-----------------
1  | '{"a:1", "b:2"}'

I'd like to insert into a new table that looks like:

table1_id | col1 | col2
------------------------
1         | 'a'  | 1
1         | 'b'  | 2
2
  • 2
    It's unclear whether those single quotes are real - at either stage. Please provide a complete setup with CREATE TABLE (showing data type and constraints) and INSERT statements (showing exact values). Commented Aug 4, 2022 at 23:49
  • @a_horse_with_no_name col1 is string, col2 is integer Commented Aug 5, 2022 at 6:24

1 Answer 1

1

You can issue an insert from this select:

select id as table1_id,
       (string_to_array(ary, ':'))[1] as col1,
       (string_to_array(ary, ':'))[2] as col2
  from table1
       cross join lateral unnest(col1) as u(ary);

db<>fiddle here

Sign up to request clarification or add additional context in comments.

2 Comments

That works great! What does u(ary) do?
The u(ary) aliases the result of the unnest(col1) as table u with one column, ary. Without that aliasing, the result of the unnest is called unnest instead of ary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.