Skip to content
Advertisement

Postgres Nested JSONB Query

I have a JSONB column, data, in the orders table:

# orders.data

{
  discount_codes: [
    { code: 'foo' },
    { code: 'bar'}
  ]
}

# codes_array: ['foo', 'bar', 'baz']

I’m trying to select “orders where discount_codes contain a code in codes_array”. I could not figure out how to write this query exactly. I read about the [*] operator but am unsure how to use it in this context.

This only searches the first element of discount_codes:

SELECT *
FROM ORDERS
WHERE data->'discount_codes'->0->'code' ?| array['foo','bar','baz']

This only searches for ‘foo’.

SELECT *
FROM ORDERS
WHERE data @@ '$.discount_codes[*].code == "foo"'

I’ve been reading the docs https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-SQLJSON-PATH but I’m a bit lost.

Advertisement

Answer

You can extract all codes into an array, then apply the ?| operator on that array:

select *
from orders
where jsonb_path_query_array(data, '$.discount_codes[*].code') ?| array['foo','bar','baz'] 

The expression jsonb_path_query_array(data, '$.discount_codes[*].code') returns ["foo", "bar"] for your sample JSON

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement