Fetch Account Records Using Apex
In Salesforce, if you only want to use Apex class and a trigger without involving Visualforce or Lightning components, you can still fetch and display records in the Debug Log (via System.debug) or manipulate them programmatically. A trigger cannot directly “display” records on the screen, but it can fetch and log them, or process them further.
Here’s a simple example that shows how to fetch the top 5 Accounts when an Account is inserted, and display them in the debug log:
Apex Code:
—————
public class AccountFetcher {
public static List<Account> getAccounts() {
return [SELECT Name, Industry, Phone FROM Account LIMIT 5];
}
}
—————–
account fetchre annonymous window
List<Account> accList = [SELECT Id, Name, Industry, Phone FROM Account LIMIT 5];
System.debug(‘Id | Name | Industry | Phone’);
System.debug(‘—————————————————————‘);
for(Account acc : accList){
String output = String.format(‘{0} | {1} | {2} | {3}’,
new List<Object>{
acc.Id,
acc.Name != null ? acc.Name : ‘null’,
acc.Industry != null ? acc.Industry : ‘null’,
acc.Phone != null ? acc.Phone : ‘null’
}
);
System.debug(output);
}
How it Works
Whenever you insert a new Account, the trigger runs.
1. The trigger calls the AccountFetcher. getAccounts () method.
2. This method queries 5 Account records from Salesforce.
3. The details are shown in the Developer Console → Logs → Debug Output.
With this setup, you can easily see the first 5 accounts every time the trigger fires. This is useful for learning Apex triggers, testing SOQL queries, and checking real-time results directly in the debug log.