1

How can I select the rows in a table having a jsonb array that has elements with a specific property ?

Eg: If the jsonb is the following

{ "list" : [
     {"name": "John", "money": 100},  
     {"name": "Dan", "money": 900}
  ]
} 

How can I select the rows having at least one element with name 'Dan' in the array ? I tried with:

select jsonb_pretty(data) from table where data -> 'list' @>  '{"name": "Dan"}';

but id does not return any rows.

4
  • what is your excepted value? the whole row or just {"name": "Dan", "money": 900} ? Commented Jan 5, 2018 at 15:22
  • 2
    SELECT jsonb_pretty(data) FROM table WHERE data -> 'list' @> '[{"name": "Dan"}]' ? Commented Jan 5, 2018 at 15:27
  • @FeanDoe Doesn't matter, I just want to be able to identify that row. Commented Jan 5, 2018 at 16:20
  • @bma Seems like this one works! Would you like to write an answer so that I can accept it? Commented Jan 5, 2018 at 16:22

1 Answer 1

1

The key here is that the JSONB value (in the column) needs to match the filter:

SELECT jsonb_pretty(data)
FROM table
WHERE data -> 'list' @> '[{"name": "Dan"}]'

Note the [] around [{"name": "Dan"}] filter.

PostgreSQL JSON/JSONB Functions and Operators documentation for further reference.

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

Comments

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.