PostgreSQL JSONB Query: Operators, Arrays and Indexes

PostgreSQL JSONB Query: Operators, Arrays and Indexes
In this article
  1. json vs jsonb: which one to query
  2. Sample setup
  3. Read values: -> vs ->>
  4. Filter rows with JSONB in WHERE
  5. Query arrays: turn JSON arrays into rows
  6. Update JSONB fields
  7. Index JSONB so queries stay fast
  8. Common mistakes
  9. Performance tips
  10. Frequently asked questions
  11. Summary

To query JSONB in PostgreSQL you use a small set of operators: -> and ->> to read a field, @> to test whether a document contains some JSON, ? to test whether a key exists, and JSON path expressions with @? for conditions inside arrays. Add the right index and these queries stay fast on millions of rows.

This tutorial builds one small orders table and walks through every common JSONB query: reading nested values, filtering in WHERE, turning arrays into rows, updating parts of a document and indexing. Every query was run on PostgreSQL 18 and the output shown is real, including the error messages you will hit along the way.

json vs jsonb: which one to query

PostgreSQL has two JSON types. json stores the exact text you sent. jsonb parses it once and stores a binary form. Input is slightly slower, but every query afterwards is much faster because nothing has to be parsed again, and only jsonb supports GIN indexes.

The binary form also changes what you get back. jsonb does not keep whitespace, does not keep key order, and keeps only the last value when a key appears twice:

SELECT '{"b": 1, "a": 2, "a": 3}'::json  AS as_json,
       '{"b": 1, "a": 2, "a": 3}'::jsonb AS as_jsonb;
Same input, two types
         as_json          |     as_jsonb
--------------------------+------------------
 {"b": 1, "a": 2, "a": 3} | {"a": 3, "b": 1}
Output

The PostgreSQL documentation recommends jsonb for most applications. Use json only if something really depends on key order or duplicate keys. Everything below uses jsonb.

Sample setup

Each order has a few normal columns and a jsonb column called details holding the status, payment, line items and tags. Run this in a scratch database (for example sudo -u postgres createdb shop, then sudo -u postgres psql -d shop).

CREATE TABLE orders (
    order_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer  text  NOT NULL,
    details   jsonb NOT NULL
);

INSERT INTO orders (customer, details) VALUES
('Asha',  '{"status": "shipped", "payment": {"method": "upi", "amount": 1499.00},
           "items": [{"sku": "BK-101", "qty": 2, "price": 499.50},
                     {"sku": "PN-220", "qty": 1, "price": 500.00}],
           "tags": ["gift", "express"]}'),
('Ravi',  '{"status": "pending", "payment": {"method": "card", "amount": 349.00},
           "items": [{"sku": "PN-220", "qty": 1, "price": 349.00}],
           "tags": ["express"]}'),
('Meera', '{"status": "delivered", "payment": {"method": "upi", "amount": 2250.00},
           "items": [{"sku": "LT-900", "qty": 1, "price": 2250.00}],
           "tags": [], "coupon": "DIWALI10"}'),
('John',  '{"status": "cancelled", "payment": {"method": "cod", "amount": 0},
           "items": [], "tags": ["refund"], "coupon": null}');
orders table with a jsonb column
CREATE TABLE
INSERT 0 4
Output

Notice two details we will use later: Ravi's order has no coupon key at all, while John's order has the key with a JSON null value. They are not the same thing.

Read values: -> vs ->>

-> returns the value as jsonb. ->> returns it as text. That single character decides what you can do with the result next.

SELECT order_id,
       details -> 'status'  AS status_jsonb,
       details ->> 'status' AS status_text
  FROM orders;
-> keeps JSON, ->> gives text
 order_id | status_jsonb | status_text
----------+--------------+-------------
        1 | "shipped"    | shipped
        2 | "pending"    | pending
        3 | "delivered"  | delivered
        4 | "cancelled"  | cancelled
Output

The jsonb result keeps the double quotes because it is still a JSON string. The text result is a plain SQL string you can compare, concatenate or cast.

Nested objects and array elements

Chain -> to walk down the document and use ->> only on the last step. Array positions start at 0. The path operators #> and #>> take the whole path as a text array, which is shorter for deep values.

SELECT order_id,
       details -> 'payment' ->> 'method'   AS method,
       details #>> '{payment,amount}'      AS amount,
       details -> 'items' -> 0 ->> 'sku'   AS first_sku,
       details #>> '{items,0,sku}'         AS first_sku_path
  FROM orders;
Walking into nested JSON
 order_id | method | amount  | first_sku | first_sku_path
----------+--------+---------+-----------+----------------
        1 | upi    | 1499.00 | BK-101    | BK-101
        2 | card   | 349.00  | PN-220    | PN-220
        3 | upi    | 2250.00 | LT-900    | LT-900
        4 | cod    | 0       |           |
Output

John's order has an empty items array, so the first item does not exist. The operators return NULL instead of raising an error. That is helpful in reports, but it also means a typo in a key name silently returns NULL rather than failing.

Subscript syntax

Since PostgreSQL 14 you can also use square brackets, like details['payment']['method']. The result is always jsonb, the same as ->:

SELECT order_id, details['payment']['method'] AS method
  FROM orders;
jsonb subscripting
 order_id | method
----------+--------
        1 | "upi"
        2 | "card"
        3 | "upi"
        4 | "cod"
Output

Subscripts are most useful in UPDATE statements, shown later. For reading, most people stick to the arrows.

Filter rows with JSONB in WHERE

Compare a text value

SELECT order_id, customer
  FROM orders
 WHERE details ->> 'status' = 'shipped';
Filter on a top-level field
 order_id | customer
----------+----------
        1 | Asha
Output

Compare numbers: cast first

->> always returns text, so cast it before comparing with a number:

SELECT order_id, customer
  FROM orders
 WHERE (details #>> '{payment,amount}')::numeric > 1000;
Numeric comparison needs a cast
 order_id | customer
----------+----------
        1 | Asha
        3 | Meera
Output

Containment with @>

@> asks: does the left document contain this piece of JSON? It works at any depth, and for arrays the order of elements does not matter. This is the operator to reach for first, because a plain GIN index on the column supports it.

SELECT order_id, customer
  FROM orders
 WHERE details @> '{"payment": {"method": "upi"}}';
Orders paid by UPI
 order_id | customer
----------+----------
        1 | Asha
        3 | Meera
Output

It also matches objects inside arrays. This finds every order with at least one line item for SKU PN-220, without unpacking the array:

SELECT order_id, customer
  FROM orders
 WHERE details @> '{"items": [{"sku": "PN-220"}]}';
Search inside an array of objects
 order_id | customer
----------+----------
        1 | Asha
        2 | Ravi
Output

Key exists: ?, ?| and ?&

? tests whether a string is a key, or an element of an array, at the top level of the value on its left. ?| means any of the strings exist, and ?& means all of them exist.

SELECT order_id, customer FROM orders WHERE details -> 'tags' ? 'express';
SELECT order_id, customer FROM orders WHERE details -> 'tags' ?| array['gift', 'refund'];
SELECT order_id, customer FROM orders WHERE details -> 'tags' ?& array['gift', 'express'];
Existence operators on the tags array
 order_id | customer
----------+----------
        1 | Asha
        2 | Ravi
(2 rows)

 order_id | customer
----------+----------
        1 | Asha
        4 | John
(2 rows)

 order_id | customer
----------+----------
        1 | Asha
(1 row)
Output

Because ? only looks at the top level, details ? 'method' returns no rows, even though every order has a method key inside payment. Write details -> 'payment' ? 'method' instead.

Missing key vs JSON null

Ravi has no coupon key, John has "coupon": null. With ->> both come back as SQL NULL, so use ? when you need to tell them apart:

SELECT order_id,
       details -> 'coupon' AS coupon_jsonb,
       details -> 'coupon' IS NULL AS sql_null,
       details -> 'coupon' = 'null'::jsonb AS json_null,
       details ? 'coupon' AS has_key
  FROM orders WHERE order_id IN (2, 4);
SQL NULL is not JSON null
 order_id | coupon_jsonb | sql_null | json_null | has_key
----------+--------------+----------+-----------+---------
        2 |              | t        |           | f
        4 | null         | f        | t         | t
Output

For Ravi, -> returns SQL NULL because the key is missing. For John, it returns the jsonb value null, which is a real value: IS NULL is false.

Query arrays: turn JSON arrays into rows

Containment tells you whether an item exists. To report on the items themselves, for example units sold per SKU, turn the array into rows. jsonb_array_elements returns one jsonb row per element. Use it in a LATERAL join so each order is paired with its own items:

SELECT o.order_id,
       item ->> 'sku' AS sku,
       (item ->> 'qty')::int AS qty,
       (item ->> 'price')::numeric AS price
  FROM orders o
 CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS item
 ORDER BY o.order_id;
One row per line item
 order_id |  sku   | qty |  price
----------+--------+-----+---------
        1 | BK-101 |   2 |  499.50
        1 | PN-220 |   1 |  500.00
        2 | PN-220 |   1 |  349.00
        3 | LT-900 |   1 | 2250.00
Output

John's order disappears because his items array is empty, so the cross join has nothing to pair it with. Use LEFT JOIN LATERAL ... ON true if you need to keep such orders.

Typed columns with jsonb_to_recordset

When the array holds objects with a known shape, jsonb_to_recordset gives you typed columns directly. You must describe the columns in the AS clause:

SELECT i.sku, sum(i.qty) AS units_sold
  FROM orders o,
       jsonb_to_recordset(o.details -> 'items') AS i(sku text, qty int)
 GROUP BY i.sku
 ORDER BY units_sold DESC, i.sku;
Units sold per SKU
  sku   | units_sold
--------+------------
 BK-101 |          2
 PN-220 |          2
 LT-900 |          1
Output

jsonb_array_length counts top-level elements, handy for queries like "orders with more than one item". It returns 0 for John's empty array.

Conditions inside arrays with JSON path

Containment only tests equality. For "any item priced above 400" use a JSON path expression. @? returns true if the path finds anything. Inside the filter, @ means the current array element.

SELECT order_id, customer
  FROM orders
 WHERE details @? '$.items[*] ? (@.price > 400)';
Any line item above 400
 order_id | customer
----------+----------
        1 | Asha
        3 | Meera
Output

To pull out the matching values rather than just filter, use jsonb_path_query. You can also pass variables as a jsonb object, which keeps the path constant when the number changes:

SELECT order_id,
       jsonb_path_query(details, '$.items[*] ? (@.qty >= 2).sku') AS sku
  FROM orders;

SELECT order_id, customer
  FROM orders
 WHERE jsonb_path_exists(details, '$.items[*] ? (@.price > $min)', '{"min": 1000}');
Extract matches and use path variables
 order_id |   sku
----------+----------
        1 | "BK-101"
(1 row)

 order_id | customer
----------+----------
        3 | Meera
(1 row)
Output

Update JSONB fields

You can change one part of a document without rewriting it by hand. Try these inside BEGIN and ROLLBACK so your sample data stays the same for the rest of the tutorial.

jsonb_set: replace or add one value

BEGIN;

UPDATE orders
   SET details = jsonb_set(details, '{status}', '"delivered"')
 WHERE order_id = 1;

UPDATE orders
   SET details = jsonb_set(details, '{payment,txn_id}', '"UPI98231"')
 WHERE order_id = 1;

SELECT details -> 'status' AS status, details -> 'payment' AS payment
  FROM orders WHERE order_id = 1;
Change status, add a nested key
   status    |                          payment
-------------+------------------------------------------------------------
 "delivered" | {"amount": 1499.00, "method": "upi", "txn_id": "UPI98231"}
Output

The new value must be valid JSON, so a string needs double quotes inside the single quotes. The fourth argument, create_if_missing, defaults to true, which is why txn_id was added.

Merge, delete keys, delete paths

UPDATE orders
   SET details = details || '{"priority": true, "status": "on_hold"}'
 WHERE order_id = 2;               -- merge: adds priority, overwrites status

UPDATE orders
   SET details = details - 'coupon'
 WHERE order_id = 4;               -- remove a top-level key

UPDATE orders
   SET details = details #- '{payment,txn_id}'
 WHERE order_id = 1;               -- remove a nested key by path

SELECT order_id, details ->> 'status' AS status, details ? 'coupon' AS has_coupon,
       details -> 'payment' AS payment
  FROM orders WHERE order_id IN (1, 2, 4) ORDER BY order_id;
||, - and #-
 order_id |  status   | has_coupon |               payment
----------+-----------+------------+--------------------------------------
        1 | delivered | f          | {"amount": 1499.00, "method": "upi"}
        2 | on_hold   | f          | {"amount": 349.00, "method": "card"}
        4 | cancelled | f          | {"amount": 0, "method": "cod"}
Output

Ravi's status was overwritten by the merge, John's coupon key is gone, and the txn_id added earlier was removed from Asha's payment object.

Note that || merges only the top level. Concatenating {"payment": {"method": "card"}} would replace the whole payment object, not just its method. For a nested change, use jsonb_set or a subscript.

Subscript updates

UPDATE orders
   SET details['payment']['method'] = '"netbanking"'
 WHERE order_id = 2;

UPDATE orders
   SET details['tags'] = details['tags'] || '["vip"]'
 WHERE order_id = 2;

SELECT details['payment'] AS payment, details['tags'] AS tags
  FROM orders WHERE order_id = 2;

ROLLBACK;
Assign with square brackets
                  payment                   |        tags
--------------------------------------------+--------------------
 {"amount": 349.00, "method": "netbanking"} | ["express", "vip"]
Output

Subscript assignment has one useful difference from jsonb_set: it creates missing parent objects. jsonb_set(details, '{shipping,city}', '"Pune"') on an order with no shipping key reports UPDATE 1 but leaves the document unchanged, because jsonb_set needs every earlier step of the path to exist. SET details['shipping']['city'] = '"Pune"' creates {"city": "Pune"} as expected. We tested both on PostgreSQL 18.

Index JSONB so queries stay fast

Four rows prove nothing about speed, so build a 200,000-row copy with similar documents:

CREATE TABLE orders_big (
    order_id  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer  text  NOT NULL,
    details   jsonb NOT NULL
);

INSERT INTO orders_big (customer, details)
SELECT 'cust_' || g,
       jsonb_build_object(
         'status',  (ARRAY['pending','shipped','delivered','cancelled'])[1 + g % 4],
         'payment', jsonb_build_object(
                      'method', (ARRAY['upi','card','cod','netbanking'])[1 + g % 4],
                      'amount', (g % 5000) + 99),
         'items',   jsonb_build_array(jsonb_build_object(
                      'sku', 'SKU-' || (g % 2000), 'qty', 1 + g % 3)),
         'tags',    CASE WHEN g % 100 = 0 THEN '["gift"]'::jsonb ELSE '[]'::jsonb END)
  FROM generate_series(1, 200000) AS g;

ANALYZE orders_big;
200,000 generated orders

GIN index for @>, ? and @?

Without an index, a containment search reads the whole table:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF)
SELECT order_id FROM orders_big
 WHERE details @> '{"items": [{"sku": "SKU-42"}]}';
Before the index
 Gather (actual rows=100.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   ->  Parallel Seq Scan on orders_big (actual rows=33.33 loops=3)
         Filter: (details @> '{"items": [{"sku": "SKU-42"}]}'::jsonb)
         Rows Removed by Filter: 66633
 Planning Time: 0.127 ms
 Execution Time: 19.221 ms
Output
CREATE INDEX orders_big_details_gin ON orders_big USING GIN (details);
Default GIN index (jsonb_ops)
 Bitmap Heap Scan on orders_big (actual rows=100.00 loops=1)
   Recheck Cond: (details @> '{"items": [{"sku": "SKU-42"}]}'::jsonb)
   Heap Blocks: exact=100
   ->  Bitmap Index Scan on orders_big_details_gin (actual rows=100.00 loops=1)
         Index Cond: (details @> '{"items": [{"sku": "SKU-42"}]}'::jsonb)
         Index Searches: 1
 Planning Time: 0.132 ms
 Execution Time: 1.208 ms
Output (same EXPLAIN after the index)

The plan changed from a parallel sequential scan to a Bitmap Index Scan on the new index. The timings are from a small test machine and only show the direction of the change. Measure on your own data.

A GIN index works only for the operators its operator class supports, and only when the operator is applied to the indexed column itself. A query written with #>> and = does not use it:

EXPLAIN (COSTS OFF)
SELECT order_id FROM orders_big WHERE details #>> '{items,0,sku}' = 'SKU-42';
Same intent, no index
 Gather
   Workers Planned: 2
   ->  Parallel Seq Scan on orders_big
         Filter: ((details #>> '{items,0,sku}'::text[]) = 'SKU-42'::text)
Output

This is the most common reason a JSONB index "does not work". Rewrite the filter with @> (or @?), or create an expression index for the exact expression you query.

jsonb_ops vs jsonb_path_ops

GIN has two operator classes for jsonb. The default, jsonb_ops, supports ?, ?|, ?&, @>, @? and @@. jsonb_path_ops supports only @>, @? and @@, but it is usually smaller and more selective.

CREATE INDEX orders_big_details_pathops
    ON orders_big USING GIN (details jsonb_path_ops);

SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS size
  FROM pg_stat_user_indexes
 WHERE relname = 'orders_big'
 ORDER BY indexrelname;
Compare index sizes
        indexrelname        |  size
----------------------------+---------
 orders_big_details_gin     | 5264 kB
 orders_big_details_pathops | 3496 kB
 orders_big_pkey            | 4408 kB
Output

After dropping the default index, @> and @? still use the jsonb_path_ops index, but a key-exists query falls back to a sequential scan:

DROP INDEX orders_big_details_gin;

EXPLAIN (COSTS OFF)
SELECT order_id FROM orders_big WHERE details ? 'coupon';
? cannot use jsonb_path_ops
 Gather
   Workers Planned: 2
   ->  Parallel Seq Scan on orders_big
         Filter: (details ? 'coupon'::text)
Output
Operator classOperators supportedChoose it when
jsonb_ops (default)? ?| ?& @> @? @@You test for key existence, or query patterns vary
jsonb_path_ops@> @? @@You only search by containment or JSON path and want a smaller index

B-tree expression index for one hot field

If most queries filter on one field with = or a range, a normal B-tree index on that expression is often smaller and faster than a GIN index on the whole document. The query must use exactly the same expression, including the cast:

CREATE INDEX orders_big_status_idx ON orders_big ((details ->> 'status'));
CREATE INDEX orders_big_amount_idx
    ON orders_big (((details #>> '{payment,amount}')::numeric));
ANALYZE orders_big;

EXPLAIN (COSTS OFF)
SELECT order_id FROM orders_big
 WHERE (details #>> '{payment,amount}')::numeric > 5090;
Expression indexes
 Bitmap Heap Scan on orders_big
   Recheck Cond: (((details #>> '{payment,amount}'::text[]))::numeric > '5090'::numeric)
   ->  Bitmap Index Scan on orders_big_amount_idx
         Index Cond: (((details #>> '{payment,amount}'::text[]))::numeric > '5090'::numeric)
Output

Note the extra parentheses around each expression in CREATE INDEX. The syntax normally requires them for an index expression; they can be left out only when the expression is a single function call.

Common mistakes

operator does not exist: text > integer

SELECT order_id FROM orders WHERE details #>> '{payment,amount}' > 1000;
ERROR:  operator does not exist: text > integer
LINE 1: ..._id FROM orders WHERE details #>> '{payment,amount}' > 1000;
                                                                ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.
Output

Fix: cast the text, (details #>> '{payment,amount}')::numeric > 1000. Do not compare as text: as strings, '999' sorts after '1000'.

operator does not exist: text ->> unknown

SELECT order_id FROM orders WHERE details ->> 'payment' ->> 'amount' > 1000;
ERROR:  operator does not exist: text ->> unknown
Output

Fix: after the first ->> you have text, not JSON, so you cannot go deeper. Use -> for every step except the last: details -> 'payment' ->> 'amount'.

invalid input syntax for type json

SELECT order_id FROM orders WHERE details -> 'status' = 'shipped';
ERROR:  invalid input syntax for type json
LINE 1: ... order_id FROM orders WHERE details -> 'status' = 'shipped';
                                                             ^
DETAIL:  Token "shipped" is invalid.
CONTEXT:  JSON data, line 1: shipped
Output

Fix: -> returns jsonb, so PostgreSQL tries to read 'shipped' as JSON, and a bare word is not valid JSON. Either compare text with details ->> 'status' = 'shipped', or compare JSON with details -> 'status' = '"shipped"'. The same error appears when you assign details['status'] = 'shipped': the value needs JSON quotes, '"shipped"'.

Other traps

  • Using ? for a nested key. It only checks the top level, so details ? 'method' found nothing in our table.
  • Expecting jsonb_set to create a missing parent object. It returns the document unchanged; use a subscript assignment instead.
  • Creating a GIN index and filtering with ->> = 'value'. That expression cannot use the GIN index; use @> or an expression index.
  • Treating a missing key and a JSON null as the same thing. Check with ? when it matters.

Performance tips

  • Pull fields you filter, join or sort on all the time out into normal columns. JSONB is best for the attributes that vary from row to row.
  • Keep documents a manageable size. The documentation points out that any update locks the whole row, and changing one key writes a new version of the whole row, which matters for table bloat and vacuum work (see MVCC and row versions).
  • One GIN index per jsonb column is usually enough, since each extra index slows down writes. Use jsonb_path_ops if you never need ?, ?| or ?&.
  • Always confirm with EXPLAIN that your query actually uses the index you built.

Frequently asked questions

How do I query a nested JSONB field in PostgreSQL?

Chain -> for each level and finish with ->> to get text, for example details -> 'payment' ->> 'method', or use the path form details #>> '{payment,method}'.

How do I query a JSONB array of objects?

To filter, use containment: details @> '{"items": [{"sku": "PN-220"}]}'. For conditions like greater than, use a JSON path with @?. To report on the elements, expand them with jsonb_array_elements or jsonb_to_recordset in a LATERAL join.

What is the difference between -> and ->> in PostgreSQL?

-> returns jsonb, so you can keep navigating or compare with JSON values. ->> returns text, ready for SQL comparisons, casts and output.

Does a GIN index help with ->> queries?

No. The default GIN operator class supports @>, ?, ?|, ?&, @? and @@, and jsonb_path_ops supports only @>, @? and @@. Neither helps ->> with =. For ->> with = or ranges, create a B-tree index on that exact expression.

Summary

  • Store documents as jsonb, not json, unless you need the original text.
  • Use -> to navigate and ->> on the last step to get text; cast before numeric comparisons.
  • Filter with @> for containment and @? for conditions inside arrays.
  • Remember ? checks only the top level, and a missing key is not the same as JSON null.
  • Expand arrays with jsonb_array_elements or jsonb_to_recordset in a LATERAL join.
  • Update with jsonb_set, ||, -, #- or subscripts; subscripts create missing parents.
  • Index with GIN (jsonb_ops or jsonb_path_ops) or a B-tree expression index, and check with EXPLAIN.
PT Ganesh

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements.

Home
SQL
PLSQL
Interview Q&A