5

I'm trying to find all rows with a certain value in an array. Currently use

select * from test 
where data -> 'systems' -> 0 ->> 'name' = 'Stardust' 
or info -> 'systems' -> 1 ->> 'name' = 'Stardust';

The systems array can theoretically be infinitely long. Is there a way to say that when any element in the array contains this value the row should be returned? The JSON data structure looks like this:

{
  "systems": [
    {"host": "example.com", "name": "Stardust", "impact": 1}, 
    {"host": "example2.com", "name": "Milkyway", "impact": 0}
  ]
}

1 Answer 1

6

You can do something like this :

  1. If the JSON contains another JSON Object
select * from test where data->'systems' @> '[{"name":"Stardust"}]';
  1. If the JSON array contains strings
select * from test where data->'systems' ? 'Stardust';

Please refer the jsonb Operators section here for more different functions you can use.

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

5 Comments

It does not seem to work for me. Look at the edit I posted about the structure of the json. Is there anything wrong with that?
Okay got it. It should be '[{"name":"Stardust"}]' not '{"name":"Stardust"}'.
yeah correct. Let me edit and update the same. I missed the brackets I think. Happy you worked it out :)
If you got the answer to your query and if you think my answer was a bit helpful then could you please mark it as answer?
This works great, thank you for putting me on the right track!

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.