1

Imagine this simple postgresql table ('json_table'):

id | data(json)
1  | {"a": 1}
2  | {"a": 1, "b": 2}
3  | {"a": 2}

I know it's possible to query for all records having a key 'a': SELECT * FROM json_table WHERE data ? 'a';

But I would like to query all records containing a json value '2'. So the result should be this:

2  | {"a": 1, "b": 2}
3  | {"a": 2}

Is this possible with a 'simple' query like the one mentioned above?

1 Answer 1

1

I do not think there is an operator which you can use in such a simple query. You can achieve this with the query below, though I do not know whether it is the simplest way:

select distinct on (id) id, data from (
    select id, data, (json_each(data)).value::text
    from json_table
    ) alias
where value = '2'
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.