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