JSONB Path Operators #>>, @?, And @@

Navigate nested JSONB with #> and #>>, test path existence with @?, and evaluate JSONPath boolean predicates directly using the @@ operator.

SqlData Fetching

Code

snippet
CREATE TEMP TABLE order_docs (
    order_id integer PRIMARY KEY,
    doc      jsonb NOT NULL
);

INSERT INTO order_docs VALUES
    (1, '{"paid": true, "ship": {"city": "Boston"}, "items": [{"sku": "A1", "qty": 4}]}'),
    (2, '{"paid": false, "ship": {"city": "Austin"}, "items": [{"sku": "B2", "qty": 1}]}');

SELECT
    order_id,
    -- #> returns jsonb and #>> returns text at a text[] path
    doc #> '{ship}' AS ship_json,
    doc #>> ARRAY['items', '0', 'sku'] AS first_sku,
    -- @? checks whether a JSONPath expression selects at least one item
    doc @? '$.items[*] ? (@.qty >= 3)' AS has_bulk_item,
    -- @@ evaluates a JSONPath predicate expression directly to boolean
    doc @@ '$.paid == true && $.ship.city == "Boston"' AS paid_boston
FROM order_docs
ORDER BY order_id;

How it works

The file runs SELECT / INSERT / CREATE statements, touching order_docs.

order_docs runs independently by establishing session-bound temporary tables inside this script so nothing needs installing beforehand and cleanup runs on exit.

What the statements actually assemble: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Putting it to use

The file sets up its own scratch surface: it builds the session-local tables it works with (order_docs), so one full run against a throwaway database is enough.

Core lines

SELECT
    order_id,
    doc #> '{ship}' AS ship_json,
    doc #>> ARRAY['items', '0', 'sku'] AS first_sku,
    doc @? '$.items[*] ? (@.qty >= 3)' AS has_bulk_item,
    doc @@ '$.paid == true && $.ship.city == "Boston"' AS paid_boston
FROM order_docs
ORDER BY order_id;
INSERT INTO order_docs VALUES
    (1, '{"paid": true, "ship": {"city": "Boston"}, "items": [{"sku": "A1", "qty": 4}]}'),
    (2, '{"paid": false, "ship": {"city": "Austin"}, "items": [{"sku": "B2", "qty": 1}]}');
CREATE TEMP TABLE order_docs (
    order_id integer PRIMARY KEY,
    doc      jsonb NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`order_docs`.