Skip to main content

JSON_ARRAY_INSERT

Inserts one or more values into a JSON array at the given positions. Existing elements at and after a position move one place to the right; $[#] appends to the end.

See also:
[SELECT] [JSON_INSERT] [JSON_ARRAY_LENGTH]


Syntax​

SELECT JSON_ARRAY_INSERT(json_array, path, value [, path, value ...]) FROM <multipartIdentifier>;

Arguments​

json_array
A JSON value containing the array.

path
The JSON path of the insertion position, for example $[0], $[1] or $[#] (after the last element).

value
The value inserted at that position.

Return Value(s)​

Returns the modified JSON string.


Examples​

Insert and append​

The first call inserts at the second position, the second appends:

SELECT JSON_ARRAY_INSERT('[1, 2, 3]', '$[1]', 'x') AS a,
JSON_ARRAY_INSERT('[1, 2, 3]', '$[#]', 'end') AS b;
|---------------|-----------------|
| a | b |
|---------------|-----------------|
| [1,"x",2,3] | [1,2,3,"end"] |
|---------------|-----------------|

Prepend to an array field​

The following query adds a value at the start of the topics array of each repository in a GitHub organization:

SELECT name, JSON_ARRAY_INSERT(topics, '$[0]', 'stackql') AS topics
FROM github.repos.repos
WHERE org = 'stackql-labs';

For more information, see https://www.sqlite.org/json1.html#jarrayins