2
 actName |       applicable       | status | id | 
-----------------------------------------------------
   test1 | {"applicable":[1,3,7]} |      1 |  1 | 
   test2 | {"applicable":[5,4,1]} |      1 |  2 |

Is it possible to check value in array applicable? E.g. if I try to find which row contains integer value 3 in row column applicable then it must returns one row that is first row.

result :

 actName |       applicable       | status | id | 
-----------------------------------------------------
   test1 | {"applicable":[1,3,7]} |      1 |  1 | 
3
  • I'm not very familiar with arrays in postgres, but from first sight I would try SELECT * FROM table WHERE applicable LIKE '%,3,%' . Commented Jan 13, 2016 at 7:43
  • PG version? Is column applicable of json or jsonb type? Commented Jan 13, 2016 at 7:45
  • applicable is json type Commented Jan 13, 2016 at 7:47

1 Answer 1

2

You need the function json_array_elements() to unnest the json array so that you can inspect it's elements. Then it is rather easy:

SELECT *
FROM my_table
WHERE id IN (
  SELECT id
  FROM (
    SELECT id, json_array_elements(applicable->'applicable')::text::int AS chk
    FROM my_table) sub
  WHERE chk = 3);

Since json values (and thus array elements) can be of any type they need to be cast to an integer using ::text::int. You need the sub-select to check for those id values that have the value 3 in the array. Note that this will return multiple rows having the same array value. If there can be multiple duplicate array values in a single row you should SELECT DISTINCT * to avoid returning the same row multiple times.

SQLFiddle

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

2 Comments

it gives error ERROR: syntax error at or near "sub"
For me it works perfectly fine, PG 9.4.5. Did you get all the parentheses right?

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.