Skip to content
Advertisement

Postgres Nested JSONB Query

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

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:

This only searches for ‘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:

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