with affected_tasks as ( select s.task_id from public.submissions s group by s.task_id having min(s.version_number) filter (where s.type <> 'amendment') = 1 and count(*) filter (where s.type <> 'amendment' and s.version_number = 0) = 0 ) update public.submissions s set version_number = s.version_number - 1 from affected_tasks a where s.task_id = a.task_id; with corrected_versions as ( select s.task_id, coalesce(max(s.version_number) filter (where s.type <> 'amendment'), 0) as corrected_current_version from public.submissions s group by s.task_id ) update public.tasks t set current_version = cv.corrected_current_version from corrected_versions cv where t.id = cv.task_id and t.current_version is distinct from cv.corrected_current_version;