Sub topic 2
Filtering, Expanding, Building, and Updating JSON
This chapter assumes you know SELECT, INSERT, UPDATE, WHERE, and JOIN. You should also know JSON syntax and have PostgreSQL 12 or later. The examples use the orders table from the previous chapter, where details is a jsonb column.
Filtering with @> and ?
The @> operator tests whether the left jsonb value contains the right one. The ? operator tests whether a top-level key exists.
SELECT id FROM orders WHERE details @> '{"status": "paid"}';
SELECT id FROM orders WHERE details -> 'shipping' ? 'city';Containment in nested arrays
Containment also works inside arrays. The right side matches when each of its elements appears in the left side.
SELECT id FROM orders WHERE details @> '{"items": [{"sku": "B7"}]}';> Note: JDBC drivers such as PgJDBC treat ? as a parameter placeholder. In those drivers, escape the operator as ??.
Turning arrays and objects into rows
jsonb_array_elements returns one row for each array element. CROSS JOIN LATERAL attaches each element to its parent order. jsonb_each does the same for an object and returns key and value columns.
SELECT o.id,
i ->> 'sku' AS sku,
(i ->> 'qty')::int AS qty
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i;Building JSON with jsonb_build_object and jsonb_agg
jsonb_build_object takes alternating keys and values and returns one object. jsonb_agg gathers many rows into one JSON array.
SELECT jsonb_build_object('customer', customer,
'total', (details ->> 'total')::numeric) AS summary
FROM orders;
SELECT jsonb_agg(jsonb_build_object('id', id, 'customer', customer)) AS all_orders
FROM orders;Updating documents with jsonb_set, || and -
jsonb_set replaces the value at a path. || merges the top-level keys of the right operand into the left. The - operator removes a top-level key. Each returns a new value, so assign it back to the column.
UPDATE orders
SET details = jsonb_set(details, '{status}', '"shipped"')
WHERE id = 1;
UPDATE orders
SET details = (details || '{"tracking": "X1"}'::jsonb) - 'shipping'
WHERE id = 1;Exercise
Write a query that returns the id of every order that contains an item with sku B7.
Show answer
SELECT id FROM orders WHERE details @> '{"items": [{"sku": "B7"}]}';