0

Table

CREATE TABLE users
(
    username   VARCHAR(128) PRIMARY KEY,
    info       JSONB
);
INSERT INTO users (username, info)
VALUES 
('Lana', '[
  {
    "id": "first"
  },
  {
    "id": "second"
  }
]'),
('Andy', '[
  {
     "id": "first"
  },
  {
      "id": "third"
  }
 ]');

So I want to find all users, whose info.id contained in array like ["first"].

request should be like:

SELECT * 
FROM users 
where jsonb_path_exists(info, '$.id ? (@ in ("first", "second", "third",...) )');

But I can't find the correct implementation

0

2 Answers 2

2

There is no IN operator in the SQL/JSON Path language. If you want to find one of many alternatives, use a regex, e.g.

select * 
from users 
where jsonb_path_exists(info, '$.id ? (@ like_regex "^(second|third)$" )');
Sign up to request clarification or add additional context in comments.

Comments

1

You need to iterate over the array elements using $[*] then use ==

SELECT * 
FROM users 
where jsonb_path_exists(info, '$[*] ? (@.id == "first" || @.id == "second" || @.id == "third")');

Or maybe collect all IDs and use the ?| operator:

SELECT * 
FROM users 
where jsonb_path_query_array(info, '$[*].id') ?|  array['first','second','third');

That would return rows that contain at least one of those values.

If you need to find rows that contain all values, use ?& instead.

2 Comments

I can, but I need to check for content in an array. (corrected description)
You can use an OR condition

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.