1

The hstore type in Postgres provides an operation to calculate the set difference (EXCEPT) of two records. Is there something similar for jsonb? The best I've got is SELECT * FROM jsonb_each('{"a":1, "b":2}'::jsonb) EXCEPT SELECT * FROM jsonb_each('{"a":1}'::jsonb), but I don't know how to convert it back to jsonb.

I want to use this to calculate the difference (the changed values) between OLD and NEW in a trigger.

3

1 Answer 1

0

As a_horse_with_no_name pointed in the comments to a blog post describing the problem that there is no operation for jsonb - jsonb, I found this solution:

DO $$
DECLARE
  OLD CONSTANT RECORD := row(12, 'Test', false, 4);
  NEW CONSTANT RECORD := row(12, 'Test', true, NULL);
  data_diff jsonb;
BEGIN
    SELECT jsonb_object_agg(key, value) INTO STRICT data_diff
    FROM (
        SELECT * FROM jsonb_each(to_jsonb(NEW))
        EXCEPT SELECT * FROM jsonb_each(to_jsonb(OLD))
    ) as t;

    raise notice '%', data_diff;
END
$$;
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Mar 16, 2022 at 10:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.