← Back to SQL, page 14

sql-0278 · Medium mid

How can you update one field inside a JSON column without rewriting the whole document by hand?

SQLite has json_set (insert or replace), json_replace (only existing keys), json_insert (only new keys) and json_remove. PostgreSQL has jsonb_set(doc, '{path}', value) and the - operator to remove keys. The engine still writes the whole value, but the expression changes only the chosen path.

Full answer
sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
  (1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
  (2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
  (3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');
sql
UPDATE events SET payload = json_set(payload, '$.amount', 25, '$.refunded', json('true')) WHERE id = 2;
SELECT json_extract(payload, '$.amount') AS amount, json_extract(payload, '$.refunded') AS refunded FROM events WHERE id = 2;
amountrefunded
251

json_set replaced the amount and added a refunded flag in one call. json_remove drops a key:

sql
UPDATE events SET payload = json_remove(payload, '$.tags') WHERE id = 1;
SELECT payload FROM events WHERE id = 1;
payload
{"type":"signup","user":{"id":7,"country":"IN"}}

PostgreSQL:

sql
UPDATE events SET payload = jsonb_set(payload::jsonb, '{amount}', '25')::text WHERE id = 2;
SELECT payload::jsonb ->> 'amount' AS amount FROM events WHERE id = 2;
amount
25

Frequent single-field updates on large documents rewrite the whole value each time, which costs disk writes and, in PostgreSQL, creates a new row version. Fields that change often are better as normal columns.

sql
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO events VALUES
  (1, '{"type":"signup","user":{"id":7,"country":"IN"},"tags":["web","promo"]}'),
  (2, '{"type":"purchase","user":{"id":8,"country":"FR"},"amount":30,"tags":["app"]}'),
  (3, '{"type":"purchase","user":{"id":7,"country":"IN"},"amount":12}');

UPDATE events SET payload = json_set(payload, '$.amount', 25, '$.refunded', json('true')) WHERE id = 2;
SELECT json_extract(payload, '$.amount') AS amount, json_extract(payload, '$.refunded') AS refunded FROM events WHERE id = 2;

UPDATE events SET payload = json_remove(payload, '$.tags') WHERE id = 1;
SELECT payload FROM events WHERE id = 1;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite: json_set, json_replace, json_insert, json_remove
  • PostgreSQL: jsonb_set and the - operator
  • The whole value is still rewritten
  • Frequently updated fields belong in columns

Common mistakes

  • Rebuilding JSON with string concatenation
  • Using json_replace and expecting it to add new keys

Follow-ups

  • How would you append to a JSON array?
  • How would you rename a key?

Tips

  • Name the SQLite function variants