1

I have a table dealers in PostgreSQL. It looks like this:

insert into dealers values
  ('{"name":"Henry", "branches":[{"importeurs":[{"akz":"SON",number:"123456"}, {"akz":"ISA",number:"456789"}]}]}'),
  ('{"name":"Mike", "branches":[{"importeurs":[{"akz":"KIN",number:"133232"}, {"akz":"BAB",number:"767676"}]}]}'),
  ('{"name":"Sam", "branches":[{"importeurs":[{"akz":"DOM",number:"125454"}, {"akz":"QEE",number:"565665"}]}]}'),;

name column is string and branches column JSONB.

My question is: How to write a select query with given BAB and 767676 to get record Mike?

I tried this

SELECT * FROM dealers WHERE branches ->'importeurs' @> '[{"akz": "BAB", "number": "767676"}]';

I expected recode Mike back, but it returns nothing.

--------------updated--------------------

In Pic:

  1. query returns result
  2. query has error ERROR: operator does not exist: jsonb @? unknown

enter image description here

1

1 Answer 1

1

branches and importeurs are both JSON arrays, so you need to pass an array to the @> operator:

select *
from dealers
where branches -> 'branches' @> '[{"importeurs": [{"akz": "BAB", "number": "767676"}]}]';

Another option is to use a JSON path query:

where branches @? '$.branches[*].importeurs[*] ? (@.akz == "BAB" && @."number" == "767676")'

Online example

Sign up to request clarification or add additional context in comments.

5 Comments

@a_horse_with_no_name thank for your response. I tried your queries, first one return nothing, second one has error, please see my update pic
@J.Z.: both work for me
@J.Z.: if the second throws an error, you are probably using an older Postgres version.
@J.Z.: yes, Postgres 11 did not have JSON path support (that was introduced in 12)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.