2

Lets say I have table called users with jsonb column called attrs with values like this:

{
  "uuid5": {
    "label": "Email",
    "value": "[email protected]"
  },
  "uuid6": {
    "label": "Last Name ",
    "value": "Yang"
  }
}

Here is a one-liner:

"attrs": { "uuid5": { "label": "Email", "value": "[email protected]" }, "uuid6": { "label": "Last Name ", "value": "Yang" }

As you can see there are uniq keys uuid5, uuid6 and so on.

How to get users with label = 'Email' and value = '[email protected]'?

In postgres docs about json functions there is a function called jsonb_each which returns set of JSON object key/value pairs. But I could not find a way to write a query based on that.

1 Answer 1

3

You need jsonb_each to iterate over all entries in the attrs colum. It will return key/value pairs where the key is the uuid and the entry is your actual JSON structure you want to inspect. You can use that in conjunction with an EXISTS condition:

select u.*
from users u
where exists (select *
              from jsonb_each(u.attrs) as t(uid,entry)
              where t.entry ->> 'label' = 'Email'
                and t.entry ->> 'value' = '[email protected]')

Online example: https://rextester.com/SHN95362

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

2 Comments

Oh I can use nested query to iterate over jsonb_each output. Got it. And there is no way to do it in one query?
@MartinZinovsky: that is one query

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.