2

There is an 'accounts' table with 'data'::jsonb field filled with:

{
    "cars": [{"body": "E-JZA80-ALFQZ", 
         "year": 1999, 
         "brand": "Toyota", 
         "model": "Vista Ardeo"} 
     ], 
    "name": "Gilbert Moore", 
    "phone": "+13222314555"
}

I trying something like: select * from accounts where data->'cars' @> '{"brand":"Toyota"}' But it doesn`t show the record. What a have missed?

0

1 Answer 1

1

Your query expects the json value in the form:

{
    "cars": {"body": "E-JZA80-ALFQZ", 
         "year": 1999, 
         "brand": "Toyota", 
         "model": "Vista Ardeo"} 
     , 
    "name": "Gilbert Moore", 
    "phone": "+13222314555"
}

But in the actual data data->'cars' is an array, not an object, so the query should be:

select a.*
from accounts a
where data->'cars' @> '[{"brand":"Toyota"}]'

as operator @> applies to two objects or two arrays.

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

2 Comments

I like the cross join solution. But what about operation cost? For example, I have 10 millions of records with 1-3 cars in each.
I think the query against 10 million rows may take one or few minutes. With large amount of data I personally would prefer to convert a json to standardized tables. Initially you have to spend extra time to design tables and insert/update functions, but in the long run it brings tangible benefits. In principle I do not use jsonb type if the number of rows may be greater than some 100 000.

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.