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
Brian SheaBrian Shea 

Concatenate a zero to the start of a string in APEX/SOQL

Hi there,
I have a custom zip code field (text field) in my application and when I recently loaded a large volume of data, I the leading zero on a few hundred of the zip codes were dropped.

I have written a SOQL query that identifies all of the records that I want to fix:

SELECT Name, Physical_Address_Zip_Code__c FROM Location__c WHERE NOT Physical_Address_Zip_Code__c LIKE '_____' ORDER BY Physical_Address_Zip_Code__c
but I want to write an apex script that concatenates a leading zero to the start of all these records. Anyone know how to do this? Thanks!
Best Answer chosen by Brian Shea
Shweta_AgarwalShweta_Agarwal
Hi Brian,

You can use for loop to iterate over the list of record and upande 0 to Physical_Address_Zip_Code__c.
For example:
 
List<Location__c> locList = [SELECT Name, Physical_Address_Zip_Code__c FROM Location__c WHERE NOT Physical_Address_Zip_Code__c LIKE '0%' ORDER BY Physical_Address_Zip_Code__c];

for(Location__c con : locList ){
    con.Physical_Address_Zip_Code__c = '0'+con.Physical_Address_Zip_Code__c;
}
update locList ;

Hope it will help you.

Thanks

All Answers

Shweta_AgarwalShweta_Agarwal
Hi Brian,

You can use for loop to iterate over the list of record and upande 0 to Physical_Address_Zip_Code__c.
For example:
 
List<Location__c> locList = [SELECT Name, Physical_Address_Zip_Code__c FROM Location__c WHERE NOT Physical_Address_Zip_Code__c LIKE '0%' ORDER BY Physical_Address_Zip_Code__c];

for(Location__c con : locList ){
    con.Physical_Address_Zip_Code__c = '0'+con.Physical_Address_Zip_Code__c;
}
update locList ;

Hope it will help you.

Thanks
This was selected as the best answer
Brian SheaBrian Shea

That worked great. Thank you!

 

The only edit I made to your code was to update the WHERE clause from:

NOT Physical_Address_Zip_Code__c LIKE '0%'
back to my original condition:
NOT Physical_Address_Zip_Code__c LIKE '_____'  //5 underscore characters

Thanks for your help Shweta!