Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check a value of a key is true in postgres jsonb query

For example my table is :

CREATE TABLE mytable (
    id bigint NOT NULL,
    foo jsonb
);

and it has some values :

id   | foo
-----+-------
 1   | "{'a':false,'b':true}"
 2   | "{'a':true,'b':false}"
 3   | NULL

I want to know how to check if value of a key is true , and which operator should I use?

I want something like this that can check the value :

SELECT 1 
FROM mytable
WHERE
id=2
AND
foo['a'] is true
;
like image 805
Mojtaba Arvin Avatar asked Jan 29 '23 21:01

Mojtaba Arvin


2 Answers

The syntax foo['a'] is invalid in Postgres.

If you want to access the value of a key, you need to use the ->> operator as documented in the manual

select *
from mytable
where id = 2
and foo ->> 'a' = 'true';
like image 93
a_horse_with_no_name Avatar answered Jan 31 '23 19:01

a_horse_with_no_name


SELECT 1
FROM mytable
Where
id=2
AND
(foo ->> 'a')::boolean is true;
;
like image 34
Mojtaba Arvin Avatar answered Jan 31 '23 19:01

Mojtaba Arvin