I am using a boolean inside a jsonb
field. What I find out is that when my boolean is a string "true" the index is being used but when i used a bool it is not. I am currently using postgres 13.6 (cloud SQL).
Here is how i am creating the NONE working index:
CREATE INDEX IF NOT EXISTS my_index_name
ON my_table (field_1, field_2, ((additional_information->>'my_boolean')::bool));
Query:
SELECT *
FROM public.my_table
WHERE my_table.field_1=2644
AND (my_table.field_2 IS NOT NULL)
AND (my_table.additional_information->>'my_boolean')::boolean=FALSE
Execution plan:
Seq Scan on my_table (cost=0.00..42024.26 rows=66494 width=8) (actual time=0.169..139.492 rows=2760 loops=1)
Filter: ((field_2 IS NOT NULL) AND (field_1 = 2644) AND (NOT ((additional_information ->> 'my_boolean'::text))::boolean))
Rows Removed by Filter: 273753
Buffers: shared hit=14400 read=22094
Planning Time: 0.464 ms
Execution Time: 139.721 ms
But If I use:
CREATE INDEX IF NOT EXISTS my_index_name_text
ON my_table (field_1, field_2, (additional_information->>'my_boolean'));
Query:
SELECT *
FROM public.my_table
WHERE my_table.field_1=2644
AND (my_table.field_2 IS NOT NULL)
AND (my_table.additional_information->>'my_boolean' = 'true')
Execution plan:
Index Scan using my_index_name_text on my_table (cost=0.42..5343.80 rows=665 width=8) (actual time=0.211..7.123 rows=2760 loops=1)
Index Cond: ((field_1 = 2644) AND (field_2 IS NOT NULL) AND ((additional_information ->> 'my_boolean'::text) = 'false'::text))
Buffers: shared hit=3469
Planning Time: 0.112 ms
Execution Time: 7.241 ms
It is working. Does anyone had a similar problem ? Thanks a lot for you help!