2

I have a JSONB column in my PostgreSQL database. The data looks like this:

{
   "cars": 
      [ 
        {
          "id": 1,
          "brand": "BMW"
          "parts": 
            [
              {
                "partId": 5,
                "type": "battery"
              }
            ]
        },
        {
          "id": 2,
          "brand": "Mercedes"
          "parts": 
            [
              {
                "partId": 5,
                "type": "battery"
              },
              {
                "partId": 6,
                "type": "engine"
              }
            ]
        }
     ]
}

Is there any way that I can search for all cars that have a part with type "battery"? How can I search inside of cars array and then inside of the parts array of each car element?

1
  • What output you are expecting? Also update your version of Postgresql Database Commented Sep 9, 2020 at 8:01

1 Answer 1

1

As it's not clear in your question that what output you want. So I am assuming that you want id and brand name in output:

so you try this:

select distinct x.y->>'id', x.y->>'brand' 
from test 
cross join lateral jsonb_array_elements(data->'cars') x(y)
cross join lateral jsonb_array_elements(x.y->'parts') a(b)
where a.b->>'type'='battery'

DEMO

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

1 Comment

I've just tested your solution and it works fine. Congrats!

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.