Sub topic 12
Creating many users at once
This chapter assumes you can already create a single user in Setup, that you know how a profile relates to a user licence, and that you have checked licence capacity. It covers three ways to create users in volume: Add Multiple Users, Data Loader, and a short Apex loop. Choose by the number of users and by how much control you need over fields.
Choosing a method
Each method calls the same underlying User object, so the same rules apply to all of them. Usernames must be unique across all Salesforce orgs, the profile must be compatible with an available licence, and every required field must have a value.
| Method | Practical size | Fields you can set | Best for |
|---|---|---|---|
| Add Multiple Users (Setup) | Up to 10 users per run | A small fixed set, such as name, email, username, profile and role | A new team of a few people |
| Data Loader (insert) | Hundreds to thousands | Any field you can write on User | Onboarding waves, migrations, sandbox seeding |
| Apex | Small to medium batches | Any writable field, plus logic | Test data, automated provisioning |
The Add Multiple Users page can vary by org edition and by which user licences you own. Some orgs only offer a subset of licence types there. If a licence you need is missing, use Data Loader.
Add Multiple Users
This page is meant for small groups. Open it from Setup by searching for "Users", opening Users, and choosing Add Multiple Users.
- Select the user licence to apply to every user in this run. All rows share one licence.
- Fill in up to 10 rows. For each row, enter first name, last name, email, and a username.
- Choose a profile that matches the licence. The profile list is filtered to profiles that use the licence you selected.
- Optionally choose a role. Leave it blank if the licence has no role requirement.
- Decide whether to generate new passwords and email them to the users, then save.
Because one licence covers the whole run, create users with different licences in separate runs. If any row fails validation, correct the row and resubmit. Check the page's message to see which usernames or emails were rejected.
Preparing for Data Loader
Data Loader is the right tool once you pass a dozen users. Most failures happen before you press a button, so prepare the data carefully.
Check capacity first
An insert that needs more licences than you have will fail for the rows beyond the limit. Run the capacity query from the earlier chapter and compare the remaining count to the number of rows.
SELECT Name, TotalLicenses, UsedLicenses
FROM UserLicense
ORDER BY NameRemaining licences are TotalLicenses - UsedLicenses. If you plan to assign permission sets that require a permission set licence, check that capacity as well.
SELECT MasterLabel, TotalLicenses, UsedLicenses
FROM PermissionSetLicense
ORDER BY MasterLabelLook up profile IDs
The CSV needs a ProfileId, not a profile name. Query the Profile object and copy the IDs for the profiles you plan to use. Profile IDs differ between orgs and between a sandbox and production, so never reuse an ID from another org.
Build the CSV
Each row needs the required fields. Here is a minimal layout.
LastName,FirstName,Email,Username,Alias,ProfileId,TimeZoneSidKey,LocaleSidKey,EmailEncodingKey,LanguageLocaleKey
Lovelace,Ada,[email protected],[email protected],alove,<ProfileId>,America/Los_Angeles,en_US,UTF-8,en_US
Hopper,Grace,[email protected],[email protected],ghopper,<ProfileId>,America/Los_Angeles,en_US,UTF-8,en_USReplace <ProfileId> with a real 15 or 18 character profile ID before loading. Points to watch:
- Username must look like an email address and be unique across every Salesforce org. Adding a suffix such as
.demois a common way to avoid clashes, especially in sandboxes. - Alias is limited to 8 characters.
- TimeZoneSidKey, LocaleSidKey, EmailEncodingKey and LanguageLocaleKey take API values, not display labels.
America/Los_Angelesanden_USare valid,Pacific Timeis not. - Role is optional. To set it, add a
UserRoleIdcolumn with role IDs. - Save the file as UTF-8 so that names with accents survive the load.
A spreadsheet application can silently change values, for example by turning long IDs into scientific notation or dropping leading zeros. Open the CSV in a text editor before loading if anything looks wrong.
Run the insert
- Open Data Loader and choose Insert.
- Log in and select the User object. If it is not listed, tick the option to show all objects.
- Select your CSV.
- Map the columns. Auto-match works when headers equal the API names, as in the sample.
- Choose a folder for the result files and finish.
Data Loader writes two files. The success file lists each created row with its new user ID. The error file lists each rejected row with a message. Keep the success file, because you need the user IDs for permission set assignments.
Assigning access after the load
Creating a user does not grant extra access beyond the profile. To assign permission sets in bulk, insert records into the PermissionSetAssignment object with Data Loader. Each row needs the user ID and the permission set ID.
AssigneeId,PermissionSetId
<UserId from success file>,<PermissionSetId>If the permission set requires a permission set licence, assign that licence first. Otherwise the insert fails. Permission set licence assignments use the PermissionSetLicenseAssign object, with AssigneeId and PermissionSetLicenseId columns.
Creating users with Apex
For a small number of users, or when you want logic in the process, insert User records from Apex. This snippet runs in the Developer Console's Execute Anonymous window. It creates one user and assigns a permission set. Replace the permission set API name with a real one.
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
FirstName = 'Ada',
LastName = 'Lovelace',
Alias = 'alove',
Email = '[email protected]',
Username = '[email protected]',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US'
);
insert u;
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = 'Your_Permission_Set_API_Name' LIMIT 1];
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);When you move from one user to a list, collect users in a List<User> and insert once, using Database.insert(users, false) so that one bad row does not roll back the others. Inspect the returned Database.SaveResult array for errors. Be aware of a platform restriction: inserting a User (a setup object) and a non-setup object in the same transaction raises a MIXEDDMLOPERATION error. Do the two in separate transactions, for example with an asynchronous method.
PermissionSetAssignment is also a setup object. Inserting it together with a User record in the same transaction is allowed, as the snippet above shows, but mixing either with records such as Accounts is not.
Common failures in bulk loads
| Error message (approximate) | Cause | Fix |
|---|---|---|
| DUPLICATE_USERNAME | Username already exists in any org | Change the username; add a distinguishing suffix |
| LICENSE_LIMIT_EXCEEDED | No licences left for the profile's licence | Free licences by deactivating users or buy more |
| INVALID_CROSS_REFERENCE_KEY | Profile or role ID is wrong or from another org | Re-query IDs in the target org |
| REQUIRED_FIELD_MISSING | A required column is empty | Fill the column for that row |
| INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST | A locale or time zone value is not valid | Use the API value, such as `en_US` |
| FIELD_INTEGRITY_EXCEPTION | Email or alias is malformed, or a value does not fit | Correct the value and reload |
When some rows fail, do not reload the whole file. That would raise duplicate username errors for rows that succeeded. Instead, correct only the rows in the error file and load those.
Edge cases
- Inactive users still hold usernames. Reusing the username of a deactivated user fails with DUPLICATE_USERNAME. Rename the old user's username first, or choose a new one.
- One licence per profile. If your CSV mixes profiles from different licences, each licence needs its own capacity. A single shortfall fails only the rows that use it.
- Managers and delegated approvers are lookups to other users. Load them in a second pass after the people they reference exist.
- Time zone and locale default from the running admin only in the UI. In Data Loader and Apex you must supply them.
Exercise
You have a CSV of 40 new users that all use the Standard User profile. Data Loader reports that 32 rows succeeded and 8 failed with LICENSELIMITEXCEEDED. What do you do next, and why should you not reload the original file?
Show answer
Free or buy licences first, for example by deactivating users who have left, then confirm remaining capacity with a query on UserLicense. Load only the 8 rows from the error file. Reloading all 40 would try to create the 32 existing usernames again and fail with DUPLICATE_USERNAME, and could create confusion about which users exist.
Exercise
Your Apex script inserts a User and then an Account in the same transaction and fails with MIXEDDMLOPERATION. How do you fix it?
Show answer
Split the work into separate transactions. User is a setup object and Account is not, so they cannot be changed together. Run one of the operations in an asynchronous context such as a Queueable job or a future method.