Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONB in where clause postgres

I Have a data like this - JSONB Data

So i need to find out all rows with id=203498. How can i write a query for this ? Any Help ?

like image 419
sagar Avatar asked Apr 24 '26 06:04

sagar


2 Answers

Use the JSON containment operator @>:

WHERE jsoncol @> '[ { "id": 203498 }]';
like image 186
Laurenz Albe Avatar answered Apr 26 '26 01:04

Laurenz Albe


It depends your data so please add to example data but I will give you example data.

If your data like this

 id |                                     cars_info                                      
----+------------------------------------------------------------------------------------
  1 | {"id": 1, "sold": true, "brand": "Toyota", "color": ["red", "black"], "price": 285000}
  2 | {"id": 2, "sold": false, "brand": "Honda", "color": ["blue", "pink"], "price": 25000}
  3 | {"id": 3, "sold": true, "brand": "Mitsubishi", "color": ["black", "gray"], "price": 604520}

Your query is like this. Maybe it can occurs some errors but your query will be seem like that.

SELECT * FROM cars WHERE cars_info -> 'id' = '1';
like image 33
Süleyman Bilgin Avatar answered Apr 26 '26 00:04

Süleyman Bilgin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!