0

I have a jsonb field in a PostgreSQL table and I want to change only the key name, keeping the same value for it.

Currently, I'm doing this in Rails like this:

Event.each do |event|
   event.metadata['new_key'] = metadata['old_key']
   event.metadata.delete('old_key')
   event.save
end

Is there a way to achieve the same result using a single update_all query?

1
  • Top level key? Sample value? Postgres version? Commented Apr 17, 2019 at 18:42

1 Answer 1

2

Assuming a top-level key and current PostgreSQL,
you can achieve this by removing the old key and adding the new - with the value copied from the old:

UPDATE event
SET    metadata = (metadata - 'old_key')
               || jsonb_build_object('new_key', metadata->'old_key')
WHERE  metadata ? 'old_key';  -- only where the key exists

db<>fiddle here

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

Comments

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.