I am trying to grab a list of unique users from a subset of leads and I am running into a System.QueryException: List has no rows for assignment to SObject error.

Here is my new code below. If I get an exception in the for loop will it still continue executing?

Set<User> usr = new Set<User>();

for(Lead led : lst) {
        try {
            User lusr = [SELECT Email, Name from User where Id = :led.OwnerId LIMIT 1];
            if(!usr.contains(lusr)) {
        } catch(Exception e) {
            System.debug('**Exception: ' + e.getMessage());

Thanks for the help! This is for a scheduled Apex job.


Yes, but you should not put a query in a loop. This may run in governor limits. Instead, collect all the OwnerId values first, then query them:

Map<Id, User> owners = new Map<Id, User>();
for(Lead led: lst) {
  owners.put(led.OwnerId, null);
owners.putAll([select email, name from user where id = :owners.keyset()]);
for(Lead led: lst) {
  User u = owners.get(led.OwnerId);
  if(u != null) {

This is what I commonly call the "Aggregate-Query-Update" pattern, since you aggregate (gather together) values, perform a single query, then do some sort of post-query update.

Also note that by using this pattern, you can often avoid QueryException ("no rows for assignment") and other similar errors. In general, you should not use try-catch unless you absolutely need to, because it has a serious implication on CPU governor limits.

  • Thanks! Implementing this now. I was running into errors from some OwnerIds not being users in our system. I really appreciate the explanation too. – Patrick Fedigan Jan 17 '18 at 17:58

Even if an exception is thrown for a single record the loop will continue fetching the other records.

Attention! you are having an SOQL query inside a for loop which is not a best practice (take a look here)

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.