="with cte as (select gp.id gpid, RANK() OVER ( ORDER BY gp.id DESC) AS rnk from group_privilege gp JOIN public.organisation o ON o.id = gp.organisation_id JOIN public.groups g ON g.id = gp.group_id JOIN public.privilege priv ON priv.id = gp.privilege_id "&IF(NOT(ISBLANK(D2)), "JOIN public.subject_type st ON st.id = gp.subject_type_id", "")&" "&IFS(AND(ISBLANK(G2), ISBLANK(F2), NOT(ISBLANK(E2))),"JOIN public.program prog ON prog.id = gp.program_id", AND(ISBLANK(G2), NOT(ISBLANK(F2)), NOT(ISBLANK(E2))), "JOIN public.program prog ON prog.id = gp.program_id JOIN public.encounter_type et ON et.id = gp.program_encounter_type_id", AND(ISBLANK(E2), ISBLANK(F2), NOT(ISBLANK(G2))), "JOIN public.encounter_type et ON et.id = gp.encounter_type_id", TRUE, "")&" WHERE o.""name"" = '"&A2&"' AND g.""name"" = '"&B2&"' AND priv.""name"" = '"&C2&"' "&IF(NOT(ISBLANK(D2)), "AND st.name = '"&D2&"'", "")&" "&IFS(AND(ISBLANK(G2), ISBLANK(F2), NOT(ISBLANK(E2))),"AND prog.""name"" = '"&E2&"'", AND(ISBLANK(G2), NOT(ISBLANK(F2)), NOT(ISBLANK(E2))),"AND prog.""name"" = '"&E2&"' AND et.""name"" = '"&F2&"'", AND(ISBLANK(E2), ISBLANK(F2), NOT(ISBLANK(G2))),"AND et.""name"" = '"&G2&"'", TRUE, "")& " ) UPDATE group_privilege SET last_modified_date_time = current_timestamp + (random() * 1000 * (interval '1 millisecond')), last_modified_by_id = 5516, is_voided = cte.rnk > 1, allow = "&I2&" from cte WHERE id = cte.gpid; "