I am trying to optimize the below query which is run every 50 seconds to improve the performance.
select * from event se1
where id = (select min(id) from event se2 where
se1.sub_id=se2.sub_id and se2.state = 'PENDING' and se2.il_flag= true)
and not exists (select id from event se2 where se1.sub_id=se2.sub_id
and se2.state in ('ACCEPTED', 'FAILED', 'INPROCESS'))
Any direction on coming up with a better query to improve its performance ? ( postgres 9.6 ). Appreciate the help.
Event table
Id sub_id state idl_flag
1 23009 Pending true
2 23009 Accepted true
3 23009 Pending true
4 23009 Pending true
5 23010 Pending true
6 23010 Pending true
7 23011 Pending true
8 23012 Pending true
The above table should return
5 23010 Pending true
7 23011 Pending true