0

Would someone please show me how to do insert & update a jsonb column? Say I have this Permanent table that has 2 columns (ticker varchar(10), data(jsonb)), with ticker is the primary key: In it, it has this data

XYZ,{"sales":{"2022-06-30":1500,"2022-03-31":1200}}

Now, a new quarter has been reported and the Temp table has this data:

XYZ,{"sales":{"2022-09-30":1800}}

How can I do INSERT INTO so it update just the data(jsonb)

INSERT INTO perm_table(ticker,data)
FROM temp_table ticker,data
ON CONFLICT ????? DO NOTHING;

Thank you so much in advance for your guidance!

1 Answer 1

1

One option is to use a Common table expression(or possibly a subquery) after outer full joining tables while reconstructing the objects and completing missing values through use of COALESCE() such as

WITH j AS
(
  SELECT id_, jsonb_build_object('sales', js) AS js
    FROM (SELECT COALESCE(t.id, p.id) AS id_,
                 jsonb_object_agg(COALESCE((js_t).key, (js_p).key),
                                  COALESCE((js_t).value, (js_p).value)) AS js
            FROM (SELECT id, jsonb_each(val) AS js_t
                    FROM temp_table
                   CROSS JOIN jsonb_each(data) AS arr(key, val)) AS p
            FULL JOIN (SELECT id, jsonb_each(val) AS js_p
                        FROM perm_table
                       CROSS JOIN jsonb_each(data) AS arr(key, val)) AS t
              ON (js_p).key = (js_t).key
           GROUP BY id_) AS q
)
UPDATE perm_table
   SET data = j.js
  FROM j 
 WHERE id = id_

Demo

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

1 Comment

Mr. Ozhan, I am grateful for your taking the time to teach me again! This coding is wonderful. I would never be able to come up with it myself. Thank you!!!!

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.