can anyone explain why the first query is bit faster than the second?
explain analyze select count(*) from view_recurrence_service_plan_description a
left join (select * from vehicle_roster where cast(schedule_date as date)=current_date) vr on a.recurrence_service_plan_id=vr.recurrence_service_plan_id
left join vehicle_route vroute on vroute.vehicle_route_id=vr.vehicle_route_id
left join vehicle on vehicle.vehicle_id=vroute.vehicle_id;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=736.29..736.30 rows=1 width=0) (actual time=13.206..13.206 rows=1 loops=1)
-> Hash Left Join (cost=1.15..706.42 rows=11946 width=0) (actual time=0.041..11.401 rows=11946 loops=1)
Hash Cond: (recurrence_service_plan.recurrence_service_plan_id = vehicle_roster.recurrence_service_plan_id)
-> Seq Scan on recurrence_service_plan (cost=0.00..660.46 rows=11946 width=24) (actual time=0.010..8.170 rows=11946 loops=1)
Filter: (NOT hide)
-> Hash (cost=1.14..1.14 rows=1 width=16) (actual time=0.021..0.021 rows=0 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 0kB
-> Seq Scan on vehicle_roster (cost=0.00..1.14 rows=1 width=16) (actual time=0.021..0.021 rows=0 loops=1)
Filter: ((schedule_date)::date = ('now'::cstring)::date)
Rows Removed by Filter: 10
Total runtime: 13.286 ms
(11 rows)
=========================================================================================================================================================
explain analyze select count(*) from view_recurrence_service_plan_description a
left join vehicle_roster vr on a.recurrence_service_plan_id=vr.recurrence_service_plan_id and cast(vr.schedule_date as date)=current_date
left join vehicle_route vroute on vroute.vehicle_route_id=vr.vehicle_route_id
left join vehicle on vehicle.vehicle_id=vroute.vehicle_id;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=736.29..736.30 rows=1 width=0) (actual time=13.355..13.356 rows=1 loops=1)
-> Hash Left Join (cost=1.15..706.42 rows=11946 width=0) (actual time=0.040..11.549 rows=11946 loops=1)
Hash Cond: (recurrence_service_plan.recurrence_service_plan_id = vr.recurrence_service_plan_id)
-> Seq Scan on recurrence_service_plan (cost=0.00..660.46 rows=11946 width=24) (actual time=0.010..7.905 rows=11946 loops=1)
Filter: (NOT hide)
-> Hash (cost=1.14..1.14 rows=1 width=16) (actual time=0.020..0.020 rows=0 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 0kB
-> Seq Scan on vehicle_roster vr (cost=0.00..1.14 rows=1 width=16) (actual time=0.020..0.020 rows=0 loops=1)
Filter: ((schedule_date)::date = ('now'::cstring)::date)
Rows Removed by Filter: 10
Total runtime: 13.436 ms
(11 rows)
Im working with multiple left joins and I'm trying to optimize it. Every second counts for me. Can I use left join lateral here? Any tips on optimizing?