Soql query to get the specific year and month createddate data fetching
•15 min read

Here are the best SOQL query methods to fetch records from a specific year and month using CreatedDate, along with Apex code examples.
✅ 1. SOQL Query for Specific YEAR and MONTH
Method 1: Using CALENDAR_YEAR & CALENDAR_MONTH
SELECT Id, Name, CreatedDate
FROM Account
WHERE CALENDAR_YEAR(CreatedDate) = 2024
AND CALENDAR_MONTH(CreatedDate) = 11
JavaScript✅ 2. Using Date Literal for Entire Month
If you want records created in November 2024:
SELECT Id, Name, CreatedDate
FROM Contact
WHERE CreatedDate >= 2024-11-01T00:00:00Z
AND CreatedDate < 2024-12-01T00:00:00Z
JavaScript(This method is faster and more index-friendly.)
✅ 3. Using DATE Formats
SELECT Id, Name, CreatedDate
FROM Opportunity
WHERE CreatedDate = THIS_MONTH
JavaScriptTo fetch last month:
WHERE CreatedDate = LAST_MONTH
JavaScript✅ 4. Fetch Specific Month of Any Year
Example: All records created in May (any year)
SELECT Id, CreatedDate
FROM Lead
WHERE CALENDAR_MONTH(CreatedDate) = 5
JavaScript📌 Apex Code Example
Integer yearVal = 2024;
Integer monthVal = 11;
List<Account> accList = [
SELECT Id, Name, CreatedDate
FROM Account
WHERE CALENDAR_YEAR(CreatedDate) = :yearVal
AND CALENDAR_MONTH(CreatedDate) = :monthVal
];
System.debug('Records: ' + accList);
JavaScript📌 Apex Code Example (Using Date Range)
More efficient & recommended
Integer yearVal = 2024;
Integer monthVal = 11;
Date startDate = Date.newInstance(yearVal, monthVal, 1);
Date endDate = startDate.addMonths(1);
List<Lead> leadList = [
SELECT Id, Name, CreatedDate
FROM Lead
WHERE CreatedDate >= :startDate
AND CreatedDate < :endDate
];
System.debug('Leads: ' + leadList);
JavaScript⭐ Best Practice Recommendation
✔ Use date range filtering
✔ Avoid CALENDAR_YEAR / CALENDAR_MONTH when dealing with large data — they are slower.
Related Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
