Skip to main content
Watch live demos of top features from Winter ’25 here.
Time Estimate

Add a Method to the Class

Create a Method

A class usually contains one or more methods that do something useful. In this step, you’ll create the updateOlderAccounts method, which gets the first five Account records ordered by the date created. It then updates the description field to say that this is a “Heritage Account,” meaning accounts that are older than other accounts.

  1. In the body of the OlderAccountsUtilityclass (the information between the curly brackets), copy and paste the following method.
        public static void updateOlderAccounts() {
          // Get the 5 oldest accounts
          Account[] oldAccounts = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
          // loop through them and update the Description field
          for (Account acct : oldAccounts) {
              acct.Description = 'Heritage Account';
          }
          // save the change you made
          update oldAccounts;
        }
  2. Click File | Save.

The code first sorts Accounts by the date that they were created on. It then grabs the five oldest records. It uses the SOQL query language (line 3) to do the querying and sorting. It then iterates through each Account record to update the Description field. Finally, it updates the Account records by using the Apex Data Manipulation Language (DML). If you're familiar with Java and C#, you'll notice a lot of similarities in the syntax.

Share your Trailhead feedback over on Salesforce Help.

We'd love to hear about your experience with Trailhead - you can now access the new feedback form anytime from the Salesforce Help site.

Learn More Continue to Share Feedback