-2

Ι have the following table named discounts:

id Serialize
discount INT
offers JSON

With the following records

id discount offers
1 10 [{"type":"discount","percent":100},{"type":"freebie","id:100}]
2 0 [{"type":"discount","percent":100},{"type":"freebie","id:100}]
2 100 NULL

How I can search inside the table for all records that have non zero discount but inside the JSON that has type discount inside the JSON.

So far I have tried this query:

select * 
from discounts r 
where discount <> 0 
  and offers @> '[{"type":"discount"}]'::json;

But I get the following error:

ERROR: operator does not exist: json @> json

Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

Position: 68

0
1
CREATE TABLE discounts (id INT, discount INT, offers JSON);
INSERT INTO discounts VALUES
(1,   10, '[{"type":"discount","percent":100},{"type":"freebie","id":100}]'::JSON),
(2,   0,  '[{"type":"discount","percent":100},{"type":"freebie","id":100}]'::JSON),
(2,   100,    NULL);
SELECT * FROM discounts;
id discount offers
1 10 [{"type":"discount","percent":100},{"type":"freebie","id":100}]
2 0 [{"type":"discount","percent":100},{"type":"freebie","id":100}]
2 100 null
select * 
from discounts r 
where discount <> 0 
  and offers @> '[{"type":"discount"}]'::json;
ERROR:  operator does not exist: json @> json
LINE 4:   and offers @> '[{"type":"discount"}]'::json;
                     ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.
select * 
from discounts r 
where discount <> 0 
  and offers::JSONB @> '[{"type":"discount"}]'::JSONB;
id discount offers
1 10 [{"type":"discount","percent":100},{"type":"freebie","id":100}]

db<>fiddle here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.