0

I have a Postgres table with a json column, named raw_data, that is structured like this:

[{"id":1234, "name":"John Doe", "purchases":12}, {"id":1234, "name":"Jane Doe", "purchases":11}]

The number of sub-arrays can differ. It may be 1 or 20 or any number.

I want to perform a query where I can return the entire table row if, say, 'John Doe' occurs in the raw_data column. I already know that I can perform a query like this:

select * from my_table where raw_data->0->> 'name' = 'John Doe'

But this won't work since the int (zero in this example) is specifying the nth sub-array of the array, and I won't know which sub-array to look in ahead of time.

Is there a way to specify a search through all sub-arrays?

2
  • 1
    Sounds like time to move this data to it's own table. That will be multiple orders of magnitude faster. Commented May 10, 2022 at 18:52
  • Is there a way to perform the search I mentioned? Commented May 10, 2022 at 18:54

1 Answer 1

1

You can use a JSON path expression:

select * 
from my_table 
where raw_data @@ '$[*].name == "John Doe"';

This assumes that raw_data is a jsonb column (which it should be). If it's not, you need to cast it raw_data::jsonb

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.