// strings reference

SQL JSON_SET function

JSON_SET(config, '$.region', 'eu') returns the document with that path set: replaced if present, added if absent. It is the usual way to change one field.

カテゴリ
Strings
Returns
JSON text
In this category
146 of 172

構文

JSON_SET(json_doc, path, value [, path, value ...])

エンジンサポート

エンジンSupportメモ
SQL Server Not built in JSON_MODIFY is the equivalent
PostgreSQL Different name or syntax jsonb_set for jsonb; no json variant
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle Not built in JSON_TRANSFORM on 21c+

例

MySQL

UPDATE settings
SET config = JSON_SET(config, '$.region', 'eu');

SQLite

UPDATE settings
SET config = json_set(config, '$.tier', 'pro');

PostgreSQL

UPDATE settings
SET config = jsonb_set(config, '{region}', '"eu"');

知っておくと便利なこと

  • jsonb_set wants a text[] path and JSON-typed values: jsonb_set(config, '{region}', '"eu"'); the quoted '"eu"' is a JSON string, while bare eu is a JSON syntax error.
  • jsonb_set only creates the last path step: jsonb_set('{}', '{a,b}', '1') returns {} unchanged because a does not exist. MySQL's JSON_SET likewise skips a path whose parent is missing.
  • MySQL 8.0 can update a JSON column in place when an UPDATE uses JSON_SET, JSON_REPLACE or JSON_REMOVE on the same column and the new value is no larger. PostgreSQL always writes a new copy of the jsonb value.
  • One call can touch many paths: JSON_SET(doc, '$.a', 1, '$.b', 2). SQL Server's JSON_MODIFY takes one path per call.

Questions about JSON_SET

JSON_SET, JSON_INSERT or JSON_REPLACE?

JSON_SET does both; JSON_INSERT only creates missing paths; JSON_REPLACE only overwrites existing ones. Pick the narrow one when overwrite-or-create would be a bug.

Why does jsonb_set fail on my value?

The new value must be valid JSON in jsonb: strings need embedded quotes ('"eu"'), numbers do not. Wrap with to_jsonb(value) when the type is unclear.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.