Need to quickly check which tasks were created today in Salesforce? Want to show the top 5 most recent tasks for reporting or alerts? No problem!
In this blog post, we’ll walk through a simple Apex method that retrieves the latest five Task records created today, sorted by creation time. This kind of logic is super handy for dashboards, daily summaries, or notifications in Salesforce apps.
It’s short, sweet, and a great way to practice your SOQL skills and return lists from Apex methods. Let’s dive in!
🧠 What Are We Trying to Do?
Here’s the goal:
Query Task records created today
Sort them from newest to oldest
Return only the top 5 based on creation time
This is perfect for showing a “Recent Tasks” widget, generating a report, or sending a daily digest.
🔍 Code Explanation
public with sharing class ApexUseCaseTwelve {
public static List<Task> returnLatestTasks(){
We define a class called ApexUseCaseTwelve
and inside it, a static method called returnLatestTasks
.
This method doesn’t take any input — it simply fetches and returns data.
return [SELECT Id FROM Task
WHERE CreatedDate = TODAY
ORDER BY CreatedDate DESC
LIMIT 5];
Here’s the breakdown of the SOQL query:
SELECT Id FROM Task
: We’re only selecting theId
field here, but you can easily add more likeSubject
,Status
,OwnerId
, etc.WHERE CreatedDate = TODAY
: This filters records to only include those created today.ORDER BY CreatedDate DESC
: Sort the results so the most recently created task comes first.LIMIT 5
: Return only the top 5 results.
Once the query runs, we return the list of Task
records.
}
}
And that’s it! A clean, quick, and reusable method for fetching today’s tasks.
✅ Why This Is Useful
This method is a great example of:
Using SOQL to filter by date
Returning a list of records
Applying sorting and limits in a query
You could plug this method into:
A Visualforce page
A Lightning Web Component
A batch job that sends reminders or summaries
You can also easily extend it:
Add more fields to the query (e.g.,
Subject
,DueDate
)Make the number of records dynamic
Filter by owner or status
🧾 Final Code Snippet
public with sharing class ApexUseCaseTwelve {
public static List<Task> returnLatestTasks(){
return [SELECT Id FROM Task
WHERE CreatedDate = TODAY
ORDER BY CreatedDate DESC
LIMIT 5];
}
}
🎥 Watch It in Action!
Prefer video? Watch my short walkthrough where I demo this method in the Developer Console and explain how to tweak the SOQL for different use cases.