1

I have a column like:

[
   {
      "type":"menu",
      "prompt": {
            "type":"say",
            "message":"This is a menu. Pick option 1 or 2."
      }
   }
]

The first tier object could contain a variety of types and any number of types. My objective (for automated testing, not production, so it can be inefficient) is to find a record with any column.*.type = menu.

Based on https://stackoverflow.com/a/22687653/197606 I understand I can provide a numeric index, but running the query SELECT * FROM my_table WHERE 'my_column'->0->'type' = 'menu' throws the error:

ERROR:  operator is not unique: unknown -> integer
LINE 1: SELECT * FROM my_table WHERE 'my_column'->0->'type' =...
                                                       ^
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.
Query failed
PostgreSQL said: operator is not unique: unknown -> integer
Hint: Could not choose a best candidate operator. You might need to add explicit type casts.

While specifying a numeric index of 0 would work for this specific use case and is an acceptable answer, I'd prefer an approach that isn't picky about the column index.

4
  • Do you need this: SELECT * FROM my_table WHERE my_column->0->>'type' = 'menu' ? Commented May 4, 2017 at 19:11
  • @OtoShavadze Bingo, that was it! Commented May 4, 2017 at 19:15
  • @OtoShavadze Can you post this as an answer so I can give you credit? Commented May 13, 2017 at 15:56
  • Ok, I posted it as an answer )) Commented May 13, 2017 at 16:51

2 Answers 2

1

You can use this:

SELECT * FROM my_table WHERE my_column->0->>'type' = 'menu'
Sign up to request clarification or add additional context in comments.

Comments

0

PostgreSQL does not allow to look in json array. Your solution might be something like this:

SELECT *
FROM my_table
WHERE EXISTS (
      SELECT 1
      FROM  jsonb_array_elements(my_column) AS j
      WHERE j->>'type' = 'menu'
)

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.