Does a SOQL query select records that are locked? I have a class where it selects a record, creates another kind of record based on the data, then inserts the new record and deletes the old.

Now I am scared that a query, e.g.: [SELECT * FROM Lead WHERE condition] will also select locked records.

Could someone give me an insight on this?


Yes, it is possible to lock records. Please make sure that you are using FOR UPDATE to prevent these race conditions:

Apex allows you to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety problems. - Locking Statements

To do so you had to add to your statement FOR UPDATE. And the resulting statement would look like this:

List<Lead> leads = [SELECT ID FROM Lead FOR Update];

The result of locking is explained as well:

While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other clients have to wait until the transaction completes and the records are no longer locked before being able to update the same records. Other clients can still query the same records while they’re locked.

So it is possible to query but not to update these records.

However, to make sure that your code runs without running into race conditions, you should consider using FOR UPDATE.

Besides from locking records it is possible to generate deadlocks. Learn more about Deadlock avoidance: here.

| improve this answer | |
  • 1
    I think you misunderstood. I am asking, if the query SELECTS LOCKED records. I am not asking if I can lock records with a query. – Frederik Witte May 4 '15 at 14:42
  • @FrederikWitte the second part of this answer, answers your question, it is possible to query just not update them. – Jenny B May 4 '15 at 14:48
  • 2
    Ahh, sorry, I overread that line. Thank you for the answer! – Frederik Witte May 4 '15 at 15:03

Yes you can query (and get the ) locked records.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.