Skip to content

PostgreSQL JSONB API

PostgreSQL JSONB functions and operators for storing, querying and transforming JSON documents.

1 class · 5 methods

JSONB

5 methods

Functions and operators for the binary JSON type.

jsonb_set(target jsonb, path text[], new_value jsonb, create_missing bool = true) -> jsonb

Returns target with the field at the given path set to new_value, optionally creating it.

Parameters

NameTypeDescription
targetjsonbSource JSON document.
pathtext[]Array of keys/indices to the target field.
new_valuejsonbReplacement value.
create_missingboolIf true, creates missing keys.

Returns

jsonb

Example

postgresql
UPDATE profile
SET data = jsonb_set(data, '{address,city}', '"Berlin"', true)
WHERE id = 1;
jsonb_build_object(key text, value any, ...) -> jsonb

Builds a JSON object from alternating key/value arguments.

Parameters

NameTypeDescription
keytextObject key.
valueanyValue converted to JSON.

Returns

jsonb

Example

postgresql
SELECT jsonb_build_object('id', id, 'name', name, 'admin', is_admin) FROM users;
jsonb @> jsonb -> bool

Returns true if the left JSON value contains the right value (top-level containment).

Parameters

NameTypeDescription
leftjsonbContainer document.
rightjsonbContained document.

Returns

bool

Example

postgresql
SELECT * FROM items WHERE tags @> '["sale"]';
jsonb ? text -> bool

Returns true if the JSON object has the given top-level key, or array contains the string.

Parameters

NameTypeDescription
keytextKey or array element to test.

Returns

bool

Example

postgresql
SELECT * FROM config WHERE data ? 'feature_x';
jsonb_agg(expr ORDER BY ...) -> jsonb

Aggregates values into a JSON array, optionally ordered.

Parameters

NameTypeDescription
expranyExpression aggregated per group.

Returns

jsonb

Example

postgresql
SELECT user_id, jsonb_agg(id ORDER BY created_at) AS order_ids
FROM orders GROUP BY user_id;