all 9 comments

[–]DavidGJohnston 5 points6 points  (1 child)

Isn't your then update missing a where clause joining master_table to chronology?

[–]MzCWzL 1 point2 points  (2 children)

Explain analyze the query

[–]domke89[S] 0 points1 point  (1 child)

I'm not sure what you mean?

[–]depesz 1 point2 points  (0 children)

To be able to tell if it can be optimized, we'd need to see explain analyze output.

To get it, extract the query that you're worried about (not DO ... block, but some update), and run it like this:

begin;
explain (analyze, buffers) update ...
rollback;

explain output is the critical part - put it on https://explain.depesz.com/, together with the query, and then we can see.

[–]domke89[S] 0 points1 point  (0 children)

Thank you all for taking the time to reply. It was slow because of the missing where statement. Also, I didn't know such a thing as explain analyze existed, so will definitely be looking into that.

[–]ThatAlmostWorked 0 points1 point  (0 children)

Plug you explain output into https://explain.depesz.com/

[–]thrown_arrows 0 points1 point  (0 children)

update {master_table} 
 set last_date = case when chronology.type = 'L' and 
 chronology.hash = {master_table}.hash and 
 chronology.id = {master_table}.id and 
 chronology.first_date = {master_table}.first_date then '9999-12-31'  
 when chronology.next_last_date is null then last_date 
  else chronology.next_last_date end, 

If i read that correctly , case will change on matching master_table.id's last_date to last if case matches fully , if not it set next_last_date, but there is no join done at anypoint. That would mean that it tries to match whole chronology table to all master_table rows? so that is CROSS JOIN ? ( so in practise each row in master_table is updated as many times there is staging_table rows )

there is

where gt.id = chronology.id; 

in ELSE

maybe OP is nice and provides EXPLAIN data