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
dnakonidnakoni 

Query taking too long

I am issuing a query in Apex code (in a controller) to lookup some contacts. I am doing a limit 500 on the query, but there are about 10 million contacts in the system. When doing it through SoqlXplorer it is fast. However, when issuing the query in Apex, it takes a long time, sometimes causing the code to time out. Is there a way to speed up queries? I know it has to go through a lot of records to come up with the 500 records (in my LIMIT 500 ) but this is ridiculous. 

 

Any thoughts?

 

Thanks,

Dan

paul-lmipaul-lmi

limit statement doesn't help much unless the where clause of the query is also selective.  all limit does it reduce the size of the results returned, but it still has to go through the whole set to get those 500 if the query isn't selective enough.  also, doing things like "where x != null" is a bad idea on large data sets.

hisrinuhisrinu

You need to use where clauses to avoid the timinig issue. Preferably the where clause should be an indexed/exteral id field, this could resolve this issue.

 

You can do indexing by selecting that field as an external id or you can request salesforce to mark it as indexed.

dnakonidnakoni

Ok, but what if I have something like "where Field1 = 'yes' and field2 = 'yes' limit 500", so in essence i want to show 500 records that have those two fields as yes, how can I involve indexing in this?

 

Dan

hisrinuhisrinu

If this is the case then you might need to seek help from salesforce.

 

I believe you can/have to add some more conditions instead of only yes or no condition in your where clause.