The organization where I work as a Salesforce developer decided to upgrade a system according to Salesforce’s new update. During the upgrade, they wanted to deactivate users with specific profiles to ensure data security. I was assigned the task of deactivating all users with a particular profile.
Here, I will explain how to activate or deactivate a user from Salesforce Apex. Then, we will see how to deactivate or activate multiple users using SOQL in Apex.
Deactivate the User From Salesforce Apex
In the following program, I explained how to deactivate any user by User ID in Salesforce Apex. Here, you can see I have one activated user. We will deactivate this user using the Apex class in Salesforce.

We can deactivate users using the Apex class in Salesforce. For that, we need the User ID of the user we want to deactivate. Then, by creating an SOQL query, we can find out whether this user is active. If the user is active, then deactivate that user and update the user record.
- ID userID: I created a variable with ID as the data type and declared the user ID I want to deactivate.
- User user: Then I created a ‘user‘ variable with User as a data type to store information that we will fetch from the User object.
- If Condition: It will check whether the user who will be deactivated is currently active.
- Else: You will get the message that you entered in the else condition in the debug log.
If it is activated, then deactivate it and update the user record.
public class DeactivateUser {
public void DeactiveUser() {
ID userID = '005J3000000h8DlIAI';
User user= [SELECT Id, Name, IsActive FROM User WHERE Id = :userID];
if (user.IsActive=true) {
user.IsActive = false;
update user;
System.debug(+user.Name + 'User is Deactivated');
}
else {
system.debug('User is not Deactivated');
}
}
}
Now, we need to execute the program to open an anonymous window. Then, you need to create an object and an instance of the class.
Syntax: Class_Name instance = new Class_Name(); -> instance.Method_Name();
Then click the Execute button to execute the Apex class.
DeactivateUser d = new DeactivateUser();
d.DeactiveUser();

After executing the Apex code, navigate to the user details and refresh the page. You will see that the user has been deactivated.
