8

How do I make a SOQL query like this?

SELECT id FROM Account WHERE LastActivityDate = 30_DAYS_AGO

This produces an error:

MALFORMED_QUERY: 
Account WHERE LastActivityDate = 30_DAYS_AGO
                      ^
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Dave S
  • 599
  • 2
  • 8
  • 17
  • Are you executing this query in a web service call or in Apex code? superfell's answer is correct if this is in Apex. – Adam Butler Mar 09 '11 at 19:22
  • Via a webservice, but I just declared the date in the program and passed it as a string to the query as a specific date. – Dave S Mar 09 '11 at 20:23
  • 2
    I assumed you were using apex, as you tagged the question with apex. – superfell Mar 10 '11 at 06:54

7 Answers7

18
SELECT id FROM Account WHERE LastActivityDate = LAST_N_DAYS:30
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
ScottW
  • 421
  • 2
  • 7
16

As you're doing this from apex, you can calculate the date in apex, then bind that into your query, e.g.

date d = system.today().addDays(-30);
Account [] acc=  [select id from account where createdDate = :d];
superfell
  • 18,780
  • 4
  • 59
  • 81
9
Select Id from Account Where LastActivityDate = N_DAYS_AGO:30
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Jacob H
  • 109
  • 1
  • 1
1

LAST_WEEK and LAST_MONTH are also easy and work well.

SELECT id FROM Account WHERE LastActivityDate > LAST_MONTH

For more data look at this link: http://www.salesforce.com/us/developer/docs/officetoolkit/Content/sforce_api_calls_soql_select_dateformats.htm

n-dru
  • 9,285
  • 2
  • 29
  • 42
Cory Waz
  • 11
  • 1
0

The page of SOQL date functions appears to have moved here: https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm

To clarify, SOQL allows a date field (e.g. LastActivityDate) to be compared against a range of dates using a comparison operator. So "LastActivityDate = LAST_MONTH" is equivalent to saying that the date is greater than or equal to the start of the first day of the previous month AND less than or equal to the end of the last day.

David Crowe
  • 113
  • 6
0

Since it is 30 days ago, you an use this -

SELECT ID FROM Account WHERE LastActivityDate < LAST_N_DAYS:30
Aditya Patil
  • 548
  • 4
  • 14
0

Your query time period lies in the Date literals provided SFDC its best to use it as the time specified is a broad number , , you just need to provide the no of days and accordingly use the operator which is '=' ,'>' or '<'

LAST_N_DAYS:n       LAST_N_WEEKS:n      LAST_N_MONTHS:n     LAST_N_YEAR:n

NEXT_N_DAYS:n       NEXT_N_WEEKS:n      NEXT_N_MONTHS:n     NEXT_N_YEAR:n

your query would look simpler if you just provided the no of days / month which it falls in .

SELECT id FROM Account WHERE LastActivityDate = LAST_N_MONTHS:1

or

SELECT id FROM Account WHERE LastActivityDate = LAST_N_DAYS:30

Thanks, OQ.

SCouto
  • 7,808
  • 5
  • 32
  • 49
Quu
  • 1
  • 2