\set v_instancia random(0, 9) do $$ declare r record; begin select * into r from prueba where instancia = :v_instancia and estado = 2 limit 1 for update; update prueba set estado = 3, fecha_proceso = now() where instancia = :v_instancia and id = r.id; return; end $$ language plpgsql;