How to programmatically update a user role name I would like to update role name programmatically in Drupal 7. Does Drupal provide its own functions to do that, or do we need to query the database and  update the name manually?

Please note that this is not about changing the role a user has, but changing the name of a role.
Information about user roles should never be loaded/saved directly from the database, but using the functions the User module provides, such as:


user_role_load($rid)
user_role_load_by_name($role_name)
user_role_save()


As for changing the role name, that is not as simple as editing the role object and saving it, since the role name is required to be unique. (The name field, in the database, is the unique key for the role table.)

Before saving the role object, the code should verify the name is not already used, as the following code does.

// Load the role object from the database into the $role variable, using user_role_load()
// or user_role_load_by_name().
// The $role_name variable is assumed to contain the new name you want to give to the role.

if (!(bool) user_role_load_by_name($role_name)) {
  // There isn't a role with that name, so it's possible
  // to change the role object and save it.
  $role-&gt;name = $role_name;
  user_role_save($role);
}
else {
  // There is already a role using that name. 
  // Make the name unique, or abort the operation.
}


Using the functions made available from the User module is preferable, since it allows other modules to react to changes to roles. Those functions invoke at least one of the following hooks.


hook_user_role_insert()
hook_user_role_update()
hook_user_role_delete()
hook_user_role_presave()