Sometimes you need to quickly grab the most recently created Accounts and Contacts in Salesforce maybe to display in a dashboard, audit new entries, or just for testing and debugging.
In this blog post, we’ll walk through a simple Apex method that:
Queries the 10 most recent Account records
Queries the 10 most recent Contact records
Combines them into a single list
Returns the combined result to be used elsewhere in your code
This is a great example of using SOQL, collections, and basic logic to manipulate data in Apex.
🧠 What Are We Trying to Do?
Let’s break it down:
We want to create a method that:
Grabs the top 10 Accounts (based on
CreatedDate)Grabs the top 10 Contacts
Combines both sets into a list
Returns that list
This can help in many use cases:
Admin dashboards
Custom Visualforce or LWC components
Simple monitoring or audits
🔍 Code Explanation
We define a class called ApexUseCaseEighteen, and create a static method called displayAccAndConRecords which returns a list of generic Object type because we’re combining different SObject types (Accounts and Contacts).
We use SOQL to fetch the 10 most recently created Account and Contact records, sorted in descending order (most recent first).
We check if either list has data, and if so, we add all their entries into our final objList.
We print the total number of records fetched (for debugging), and then return the combined list.
✅ Why This Is Useful
This code is handy for:
Showing new records in the last 24 hours
Combining results from multiple objects
Building audit tools or dashboards
Bonus Tip 💡:
If you only want records created in the last 24 hours, you can filter using SOQL date functions like:
Update your queries like so:
This ensures only records from the last 24 hours are fetched!
🧾 Final Code Snippet
🎥 Watch It in Action!
Want to see how this works in the Developer Console? Watch my short demo where I query records live and explain each step in real time.
Want to go further with this?
Learn it step by step in a course, or talk it through on a 1:1 call.
