Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through columns within a row

I have a row, let it be in this format

DECLARE
    a t1%ROWTYPE;
BEGIN 
    SELECT * INTO a FROM t1 WHERE id=<some_id> 
    -- a = id: <some_id>, name: "some_name", description: "some_descr"
END;

And I need to insert one row per column into t2

t2 TABLE 
column_name TEXT, value JSONB

Excepted result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

column_name | value
--------------------
id          | '"some_id"'
name        | '"some_name"'
description | '"some_descr"'

How can I do it?

>Solution :

No need for PL/pgSQL or a loop. You can convert the row from t1 to a JSON value, then turn those key/value pairs into rows:

insert into t2 (column_name, value)
select x.col, to_jsonb(x.val)
from t1 
   cross join jsonb_each_text(to_jsonb(t1)) as x(col, val)
where t1.id = 42;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading