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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What objects does the SQL involve?
- The references are `playlists`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.