SQL JSON_INSERT function
JSON_INSERT(config, '$.created', NOW()) adds the key only if it is missing, so re-running the statement never overwrites the first value.
- 类别
- Strings
- Returns
JSON text- In this category
- 147 of 172
语法
JSON_INSERT(json_doc, path, value [, path, value ...])
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | no JSON_INSERT; JSON_MODIFY overwrites |
| PostgreSQL | Not built in | jsonb_insert errors on an existing key; 'new'::jsonb || doc keeps existing keys |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | JSON1 functions |
| Oracle | Not built in | JSON_TRANSFORM on 21c+ has add semantics |
示例
MySQL
UPDATE settings SET config = JSON_INSERT(config, '$.created', NOW());
SQLite
UPDATE settings SET config = json_insert(config, '$.note', 'first');
值得了解
- Existing paths are left untouched: run it twice and the second run changes nothing. If overwrite is wanted, that is JSON_SET.
- An array index past the end appends: JSON_INSERT('{"tags":["a"]}', '$.tags[5]', 'x') gives ["a", "x"] on MySQL. SQLite's spelling for append is '$.tags[#]'.
- PostgreSQL's jsonb_insert raises 'cannot replace existing key' instead of skipping. For insert-if-missing on objects, put the defaults on the left: '{"created": "2026-01-01"}'::jsonb || config, since the right side wins.
Questions about JSON_INSERT
Insert, set or replace?
INSERT creates only; REPLACE overwrites only; SET does both. Using JSON_SET where insert-only semantics matter silently overwrites data the caller did not mean to touch.
How do I append to a JSON array?
MySQL: JSON_ARRAY_APPEND(doc, '$.tags', 'new'). SQLite: json_insert(doc, '$.tags[#]', 'new'). PostgreSQL: tags = tags || '"new"'::jsonb.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
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.