Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select "WHERE IN" with PostgreSQL and JSONB

Given table_a like this:

 id | name
----+------
  1 | aaaa
  2 | bbbb
  3 | cccc

I can obviously issue the following query:

SELECT * FROM table_a WHERE name IN ('aaaa', 'bbb');

But given table_b like this:

 id |       data
----+------------------
  1 | {"name": "aaaa"}
  2 | {"name": "bbbb"}
  3 | {"name": "cccc"}

How do I issue a query "give me all the rows where the value of the key name is contained in this list of values?"

I know I can use the jsonb operator @> to check for each combination, but unfortunately I'd have to issue as many queries as the number of values I want to check against. Is there a way to do it in one query?

UPDATE:

I found a solution right away:

select * from table_b where data #>> '{name}' IN ('aaaa', 'bbb');
like image 690
rhymes Avatar asked Mar 27 '26 09:03

rhymes


1 Answers

SELECT * FROM table_a WHERE data->>'name' IN ('aaaa', 'bbbb')

seems like it's what you want?

like image 77
Alex Gaynor Avatar answered Mar 28 '26 23:03

Alex Gaynor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!