My table structure:
table_a(id, company_id, approval_status, is_locked)
table_b(tba_id, status)
My Query:
SELECT COUNT(id) filter (WHERE approval_status = 2
AND is_locked = true AND EXISTS
(SELECT 1 from table_b WHERE table_b.tba_id = table_a.id
AND table_b.status = 2)
FROM table_a
GROUP BY company_id
I currently have the following index, but the performance is still slow:
CREATE INDEX multiple_filter_index ON table_a (approval_status, is_locked)
Can the performance of this query be improved by adding better indexes?
Here is the Query plan:
HashAggregate (cost=463013.07..463013.10 rows=2 width=11) (actual time=47632.476..47632.476 rows=2 loops=1)
Group Key: table_a.company_id
-> Seq Scan on table_a (cost=0.00..3064.62 rows=100062 width=11) (actual time=0.003..23.326 rows=100062 loops=1)
SubPlan 1
-> Seq Scan on table_b (cost=0.00..477.27 rows=104 width=0) (actual time=1.430..1.430 rows=0 loops=33144)
Filter: ((tba_id = table_a.id) AND (status = 2))
Rows Removed by Filter: 17411
SubPlan 2
-> Seq Scan on table_b table_b_1 (cost=0.00..433.73 rows=5820 width=4) (never executed)
Filter: (status = 2)
Planning time: 0.902 ms
Execution time: 47632.565 ms