1

I have a jsonb column in postgres db. I need to query for an existence of specific key "ssn" in the json stored in the column. This key is not a top level key, but is nested. I wrote a query similar to below but it doesn't seem to retrieve the appropriate columns -

select * from application where content ? 'ssn';

When I run the above query with top level keys , it works.

{  
   "name":"bob",
   "business":{  
      "ssn":"XXXXXXXX",
    }
}
2
  • Can you provide a sample of json that is not retrieved by this query? Commented Feb 15, 2018 at 17:11
  • @IvanMogila added a sample. actual payload is much larger Commented Feb 15, 2018 at 17:33

3 Answers 3

2

If you know all possible locations of ssn key you can use query:

select *
from application
where content #> '{business,ssn}' is not null
  or content #> '{whatever,deep,ssn}' is not null;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Ivan. I just added additional question under Haleemur's answer.
2

use a extract-element-at-path operator #>> and check whether the value at the given path is null.

example:

WITH test(col) AS (
SELECT UNNEST(
  ARRAY['{"name": "bob", "business": {"ssn": "abcd"}}'::jsonb, 
        '{"name": "jen", "business": {"ssn": "1234"}}',   
        '{"name": "kay", "nonprofit": {"no-ssn": "no-ssn"}}'
        '{"name": "todd", "business": {"no-ssn": "no-ssn"}}']
))
SELECT * FROM test
WHERE col#>>'{business, ssn}' IS NOT NULL

2 Comments

Thanks @Haleemjur Ali. This works fine for the example , but doesn't work in a scenario say where business element is an array under another root element. How can I handle arrays as part of this query?
add a better example, if you want help making a solution that works.
1

you

  1. either have to write the recursive query to parse the structure of json and check for the key in every branch,
  2. or simply match pattern against text representation of jsonb

smth like:

select * from application 
where content::text like '%"ssn":%';

Comments

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.