jsonb_insert Adds Nested Array Elements

Insert into jsonb arrays and objects with jsonb_insert, choose before or after the target index, and persist the change with UPDATE.

SqlData Integrity

Code

snippet
CREATE TABLE playlists (
  id int PRIMARY KEY,
  document jsonb NOT NULL
);

INSERT INTO playlists (id, document)
VALUES
  (1, '{"name":"focus","tracks":["alpha","gamma"]}'),
  (2, '{"name":"commute","tracks":["beta"]}');

-- Insert before index 1 by default.
SELECT jsonb_insert(document, '{tracks,1}', '"beta"') AS inserted
FROM playlists
WHERE id = 1;

-- insert_after=true appends after the target element.
SELECT jsonb_insert(document, '{tracks,1}', '"delta"', true) AS inserted_after
FROM playlists
WHERE id = 1;

-- The path may also add a new object key.
SELECT jsonb_insert('{"name":"focus"}'::jsonb, '{owner}', '"ada"') AS added_key;

-- The stored document changes only after an UPDATE.
UPDATE playlists
SET document = jsonb_insert(document, '{tracks,0}', '"intro"')
WHERE id = 2;

SELECT id, document->'tracks' AS tracks
FROM playlists
ORDER BY id;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with playlists among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The playlists table is the working surface here.

Statements that matter

SELECT jsonb_insert(document, '{tracks,1}', '"delta"', true) AS inserted_after
FROM playlists
WHERE id = 1;
SELECT jsonb_insert(document, '{tracks,1}', '"beta"') AS inserted
FROM playlists
WHERE id = 1;
UPDATE playlists
SET document = jsonb_insert(document, '{tracks,0}', '"intro"')
WHERE id = 2;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `playlists`.