I have an update query that goes like this:
update table_1
set col_1='64e27e3e-833e-4d2f-be34-452727e07822'
from table_1 left join table_2 on table_2.id = table_1.id
where
table_1.col_1='64e27e3e-833e-4d2f-be34-452727e07822'
and table_1.registered_at between '2022-07-01' and '2022-08-20'
and table_2.restaurant_id = 158;
There are only 237 records to update, and the following select works instantly:
select * from table_1 left join table_2 on table_2.id = table_1.id
where
table_1.col_1='64e27e3e-833e-4d2f-be34-452727e07822'
and table_1.registered_at between '2022-07-01' and '2022-08-20'
and table_2.restaurant_id = 158;
The longest I've seen this query to run was about 7 minutes. My first guess was that it locks something that is updated during oltp, but when I run this query, pg_locks doesn't reveal any queued (that is, non-granted) locks. Besides, if I set lock_timeout to '1000ms';
the statement continues to run after 1 second passes; so it's not locks. That query terminates only after statement_timeout
passes, so it must be the query itself which is executed for so long. And the rows updated in this query are not updated by any other queries -- I intentionally took the records that were registered in the past.
So, what does it take so long?
EXPLAIN ANALYZE
with the query. But unless you're trying to solve an actual performance issue of another query by modeling it with this one, the answer to fixing this random query becomes moot because it'll likely involve just rewriting it as another random query.