0

I have a Postgres table called pricing_rule that has a column called items of type json that saves records as a JSON Array example

[{"item_code":"Nivea Men Box (12.0 PC)","name":"5e0648a9e5","uom":null},{"item_code":"Dove Men Box (6.0 Box)","name":"d805f9bb9d","uom":null}]

How should I find the items whose item_code = 'Nivea Men Box (12.0 PC)' I came up with this:

select items->>'item_code' from pricing_rule where item_code->'Nivea Men Box (12.0 PC)';

but the item_code is not getting recognised. Anyhelp is appreciated.

1
  • This would be so much easier with a properly normalized data model. Commented Aug 26, 2022 at 6:33

1 Answer 1

1

You can use the contains operator @> to find the rows that contain that item code:

where items @> '[{"item_code": "Nivea Men Box (12.0 PC)"}]

If you also want to extract the matching array element, you can use a JSON path expression:

select jsonb_path_query_first(items, '$[*] ? (@.item_code == "Nivea Men Box (12.0 PC)")')
from pricing_rule
where items @> '[{"item_code": "Nivea Men Box (12.0 PC)"}]

This assumes that items is a jsonb column (which it really should be). If it's not you need to cast it: items::jsonb @> ...

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

1 Comment

Hi @a_horse_with_no_name what should be here jsonb_path_query_first am a bit lost

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.