Please, help to optimize my query:
select id, paid_till, rating, paid
from lots
left join (select 1 paid) paid on current_timestamp <= lots.paid_till
order by paid asc, rating desc, updated_at desc;
And query plan:
Sort (cost=1948.17..1948.18 rows=4 width=28) (actual time=0.703..0.704 rows=4 loops=1)
Sort Key: (1), lots.rating DESC, lots.updated_at DESC
Sort Method: quicksort Memory: 25kB
-> Nested Loop Left Join (cost=0.00..1948.13 rows=4 width=28) (actual time=0.014..0.682 rows=4 loops=1)
Join Filter: (now() <= lots.paid_till)
Rows Removed by Join Filter: 2
-> Seq Scan on lots (cost=0.00..1948.04 rows=4 width=24) (actual time=0.008..0.675 rows=4 loops=1)
-> Materialize (cost=0.00..0.03 rows=1 width=4) (actual time=0.001..0.001 rows=1 loops=4)
-> Result (cost=0.00..0.01 rows=1 width=0) (actual time=0.000..0.000 rows=1 loops=1)
Planning time: 0.210 ms
Execution time: 0.724 ms
What indices I should add? How can I fix "nested loop left join"?
P.S. I can't use virtual column in select for ordering, cause Rails issues.
paidfirst. Without left join I get only paid.paid_till. I believe you would still get anested loop left joinbut it would hit the index instead of the table. Since it's a timestamp, I'm not certain you would see any performance improvement. I agree with @a_horse_with_no_name about needing realistic data in your dev table though. The optimizer needs stats on par with production to make the best execution plan. Right now it's making the best plan by using the nested loop left join. Less than 1 millisecond.