0

I have table field jsonb type and having below data.

{"roles": ["7", "73", "163"]}

I have to check "73" is present into or not by postgresql.

I have already search but the only gives solution for object of object not object of array.

I have tried below query but it does not work

SELECT * 
FROM table 
WHERE field->'roles' ? ARRAY ['73'];

--updated--

also I need only that record which have exact value

{"roles": ["7"]}

{"roles": ["7", "73", "163"]}

i.e. field only have "7" not anything else in it.

3
  • Why do you use ARRAY['73']? Your query works fine with just WHERE field -> 'roles' ? '73'. Commented Nov 8, 2016 at 10:25
  • 1
    @Marth: Thanks I have search over half day for solutions on internet and stack overflow but you give it in a minute. Commented Nov 8, 2016 at 10:31
  • @Marth: Also I need to match exact array of that. May be that's why I am using ARRAY['73'] but it does not works :( Commented Nov 8, 2016 at 10:58

1 Answer 1

1

By the documentation https://www.postgresql.org/docs/current/static/functions-json.html#FUNCTIONS-JSONB-OP-TABLE for all your cases:

Does –single– key exists in json array:

SELECT  * 
FROM    table 
WHERE   field -> 'roles' ? '73';

Does -any- of the keys at right exists in json array:

SELECT  * 
FROM    table 
WHERE   field -> 'roles' ?| ARRAY[ '7', '163' ] ;

Does -all- of the keys at right exists in left json array:

SELECT  * 
FROM    table 
WHERE   field -> 'roles' ?& ARRAY[ '7', '163' ] ;

Does left json array match -exactly- with the right json array:

SELECT  * 
FROM    table 
WHERE   field -> 'roles' = $$[ "7" ]$$::jsonb ;

Hopefully helps :)

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

1 Comment

Thanks It helps me a lot. :)

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.