AI Hints
Home›PostgreSQL Tutorial›Updating and Building JSON
PostgreSQL · Lesson 43 of 120

Updating JSONB

Change one key.

⏱ 2 min read▶ Video at 37:26🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A customer switches off the newsletter. We don't want to rewrite their whole preferences document, just one key. Postgres has operators and functions for that.

  • One key changes
  • Keep the rest
  • jsonb_set

Change, add and remove keys

Jsonb set changes the value at a path. The double bar merges in new keys. The minus operator removes a key. Run it. Customer two's preferences, after each change.

query.sqlsql
UPDATE customers SET prefs = jsonb_set(prefs, '{newsletter}', 'false')
WHERE customer_id = 2 RETURNING prefs;

UPDATE customers SET prefs = prefs || '{"format": "audiobook"}'
WHERE customer_id = 2 RETURNING prefs;

UPDATE customers SET prefs = prefs - 'genres'
WHERE customer_id = 2 RETURNING prefs;
Output
                     prefs
-----------------------------------------------
 {"genres": ["Thriller"], "newsletter": false}
(1 row)

UPDATE 1
                                prefs
----------------------------------------------------------------------
 {"format": "audiobook", "genres": ["Thriller"], "newsletter": false}
(1 row)

UPDATE 1
                    prefs
----------------------------------------------
 {"format": "audiobook", "newsletter": false}
(1 row)

UPDATE 1

Update tools

Jsonb set replaces a value at a path. Double bar merges objects, with the right side winning. Minus removes a key, and hash minus removes a path. Every update writes a new version of the whole row.

keyvalue
jsonb_setreplace at path
||merge
- 'key'remove key
#- '{path}'remove path

Summary

Jsonb set, merge and minus change parts of a document. Next, building JSON from tables.

Key takeaways
  • jsonb_set
  • ||
  • -
Next up: Building JSON — tables to JSON