Why is my SOQL query slow the first time, faster subsequently?

I am trying to understand how Salesforce executes a SOQL query. I have a query and when i run it for the first time (using Workbench, Developer Console or from the page) it takes more than a minute to return the results. But running the query second time or as many times after that it returns the same results in milliseconds. What could be the cause of this behavior?


Short Answer: because its a RDMBS backing it.

Longer Answer: Your data is ultimately stored as blocks on some storage device somewhere, if not recently access the database will have to go read those blocks into memory before it can run the query, the larger the number of blocks that need to be scanned that aren’t cached the longer this will take (note, this is related to all the data needed to execute the query, not the number of returned rows). Once read, these blocks will remain in memory in a db level cache. If you execute the same or similar query again shortly after, all that very expensive I/O can be skipped and the query executed against the already cached blocks.

Source : Link , Question Author : Sahil , Answer Author : superfell

Leave a Comment