function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vishal SawVishal Saw 

Write a trigger that enforces a custom "Account Number" generation logic, ensuring that all newly created Account have a unique account number in the format "ACCT-YYYY-XXXX" where "YYYY" represent the current year and "XXXX"represents sequential no 0001n

Help to create this on apex
SubratSubrat (Salesforce Developers) 
Hello Vishal ,

Please check with the below code and let me know if any issue arises :
trigger AccountTrigger on Account (before insert) {
    // Generate current year
    Integer currentYear =;
    // Query existing Account records with the current year
    List<Account> existingAccounts = [SELECT Account_Number_c FROM Account WHERE Account_Number_c LIKE 'ACCT-' + String.valueOf(currentYear) + '-%'];
    // Create a map to store the sequential numbers for each year
    Map<Integer, Integer> yearSequentialNumberMap = new Map<Integer, Integer>();
    // Iterate through existing Account records and populate the map
    for (Account acc : existingAccounts) {
        String accountNumber = acc.Account_Number__c;
        Integer year = Integer.valueOf(accountNumber.split('-')[1]);
        Integer sequentialNumber = Integer.valueOf(accountNumber.split('-')[2]);
        if (!yearSequentialNumberMap.containsKey(year) || sequentialNumber > yearSequentialNumberMap.get(year)) {
            yearSequentialNumberMap.put(year, sequentialNumber);
    // Generate account numbers for new Account records
    Integer sequentialNumber = yearSequentialNumberMap.containsKey(currentYear) ? yearSequentialNumberMap.get(currentYear) + 1 : 1;
    for (Account acc : {
        acc.Account_Number__c = 'ACCT-' + String.valueOf(currentYear) + '-' + String.format('%04d', sequentialNumber);

If this helps , please mark this as Best Answer.
Thank you.
Bryan Leaman 6Bryan Leaman 6
I know you said "Write a trigger", but wouldn't it be easier/better to use an auto-number field?
Autonumber field

If not, then Subrat's solution is pretty good, but will encounter performance issues or just fail if you have too many accounts added in 1 year, as the query could exceed salesforce limits.  You could try limiting the return results to the most recently-created account or accounts, but it seems risky.