0
votes

I am currently storing data in a jsonb column on a postgres db in the following format: {"ids": [4, 3, 2, 1]} where the value is an array of integers.

I wish to do the following:

  1. Locate rows where the column contains the value of 4 in the value
    array for the 'ids' key.

  2. Locate rows where the column contains the values 2,3, & 1 in the value array for the 'ids' key.

My most recent attempt use the following

select * from tablename WHERE (column_name -> ids)::integer[] && ARRAY[1,3]

Which gave me a type casting error at ::integer[] ERROR: cannot cast type jsonb to integer[]

I suspect I was trying to cast the 'ids' portion and needed to go a level deeper, but I'm unsure how (if that is even the right approach).

2

2 Answers

1
votes

Use the contains operator @>

select * 
from tablename 
WHERE column_name @> '{"ids":[4]}'

This also works for multiple values:

select * 
from tablename 
WHERE column_name @> '{"ids":[1,2,3]}'

Online example

0
votes
SELECT * from tablename WHERE column_name -> 'ids' @> '[4]'::jsonb
SELECT * from tablename WHERE column_name -> 'ids' @> '[2,3,1]'::jsonb