1

Folks,

I have a following table in my PostgreSQL.

CREATE TABLE public.my_table
(
    id uuid NOT NULL,
    name character varying(50) NOT NULL,
    field1 jsonb NOT NULL
)

I keep JSON array in my field1 as per example below:

[
    {
        "id": "abc"
    },
    {
        "id": "def"
    },
    {
        "id": "ghi"
    }
]

My question is: How do I query for rows that include a specific "id" in that JSON array?

Thanks for your help! Cheers!

1
  • could you show us sample data in tabular form? Commented Apr 27, 2020 at 23:10

2 Answers 2

1

You can use the contains operator:

select * from my_table where field1 @> '[{"id":"whatever"}]'

This operation is able to make use of an index on field1, while a method that relies on jsonb_array_elements cannot be indexed.

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

1 Comment

This is even better than the one from @GMB. I love it! Thanks a lot!
1

One option uses exists and jsonb_array_elements():

select *
from my_table t
where exists (
    select 1 from jsonb_array_elements(t.field1) f(obj) where f.obj ->> 'id' = 'abc'
)

1 Comment

Great stuff! That's what I need. Thx mate!

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.