function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sanjay WadgeSanjay Wadge 

SOQL for cases created or modified between last 24 hours

Hi,

I am trying to wirte a query in apex class to get the list of cases created between last 24 hours.
I tried following and nothing works. Every query gives some or the other syntax errors.

SELECT ID from Cases WHERE CreateDate = LAST 1 DAYS

SELECT ID from Cases WHERE CreateDate > NOW()-1 and CreateDate < NOW()

SELECT ID from Cases WHERE CreateDate > TODAY()-1 and CreateDate < TODAY()

I also tried - Cases c = new Cases [CreateDate = TODAY()];

Also I want to store ID, either in string array or list. (Sorry I am new to Apex).
Please suggest what I am doing wrong and possible solution.

-Sanjay
Shailesh DeshpandeShailesh Deshpande
Hi Sanjay,

You can use:

List<Case> cases = new List<Case>();
cases = [Select Id from Cases where CreatedDate = YESTERDAY];

User-added image

But this will count 24hrs from 12.00 midnight yesterday. If you want 24hrs from current time, you need to add some code as below:
DateTime currTime = System.now();
DateTime 24hrBefore = currTime.addHours(-24);

List<Case> cases = [Select Id from Case where CreatedDate < :currTime and CreatedDate> 24hrBefore];

Thanks,
Shailesh.
William LópezWilliam López
Hello Sanjay,

If you are new in apex you will find Date on Salesforce are easy, there is a lot of literrals and helpers.

Option 1
You can use LAST_N_DAYS
For the number n provided, starts 12:00:00 of the current day and continues for the last n days.
http://www.salesforce.com/us/developer/docs/officetoolkit/Content/sforce_api_calls_soql_select_dateformats.htm

Example:
List<Case> cases = [SELECT ID from Case WHERE CreateDate = LAST_N_DAYS:1];

Option 2
Or if its a custom date exactly 24 hours, you can use the Datetime class:
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_datetime.htm#apex_System_Datetime_addHours 

Example:
DateTime rightNow =  DateTime.now();
DateTime d24hAgo = rightNow.addHours(-24);
List<Case> cases  = [SELECT ID from Case WHERE CreateDate < :d24hAgo];

I hope it helps.

Regards,
Bill

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.

 
Suraj Tripathi 47Suraj Tripathi 47

Hi Sanjay,

You can use Last_N_Days.
Your query is:
SELECT ID from Cases WHERE CreateDate = LAST 1 DAYS-->Syntax is incorrect
So the query looks like this:
List<Case> cases = [SELECT ID from Case WHERE CreateDate = LAST_N_DAYS:1];

If you find your Solution then mark this as the best answer. 

Thank you!

Regards 
Suraj Tripathi