1

Given a jsonb column called pairs with data such as the following in a single record:

{ "foo": 1, "bar": 2 }

How to query for records where a given value is one of the values in the above field.

For example, query for 1 would match the above record.
Query for 3 would not match.

PostgreSQL 9.5

1 Answer 1

1

In Postgres 9.5 use the function jsonb_each_text() in a lateral join:

with my_table(pairs) as (
values 
    ('{ "foo": 1, "bar": 2 }'::jsonb)
)

select t.*
from my_table t
cross join jsonb_each_text(pairs)
where value = '1';

Upgrade to Postgres 12 and use json path functions, e.g.:

select *
from my_table
where jsonb_path_exists(pairs, '$.* ? (@ == 1)')

Read more: JSON Functions and Operators.

5
  • Is it possible to do this in PostgreSQL 9.5 without the with and cross join clauses? Only using select and left join or inner join?
    – B Seven
    Commented Dec 31, 2019 at 1:05
  • 1
    The with statement is not necessary, in this example it is like your original table. The cross join does not mean the Cartesian product here because it is a lateral join. But you can replace it with left join if you wish. See Db<>fiddle.
    – klin
    Commented Dec 31, 2019 at 1:18
  • Thank you. Is it possible to do it in Postgres 9.5 without a JOIN? That is, with only a WHERE clause?
    – B Seven
    Commented Dec 31, 2019 at 16:31
  • 1
    Practically not. If you have a primary key (or a unique column) you can try to use jsonb_each_text() in a WHERE clause but the lateral join is simpler and faster. The main point is that there is no function in 9.5 like jsonb_path_exists(), so you have to use the set returning function jsonb_each_text().
    – klin
    Commented Dec 31, 2019 at 17:06
  • Thanks for your help!
    – B Seven
    Commented Jan 3, 2020 at 19:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.