with x as ( select gl.id ,gl.company_id ,gl.call_group ,gl.line ,gl.priority ,gl.delay ,row_number() over(order by gl.line) new_priority from groups_line gl where gl.company_id = 181 and call_group = 1) update groups_line gl2 set priority = ( select x.new_priority from x where x.id = gl2.id ) where (gl2.id, gl2.priority) not in ( select x.id ,x.new_priority from x where x.id = gl2.id) and gl2.id in ( select x.id from x);