I am working on a CSV data upload via email to apex where if the account record exists i need to get the Id and perform an upsert operation. I am using Map to capture all the accounts and checking if the account with that name exists.

Map<String, Id> accountMap = new Map<String,Id>();
for(Account a:[SELECT Name,Id FROM Account]){

The above debug statement gives me a count of 4919.

However when i execute the following statement

System.debug([SELECT count() FROM Account]);

I get a total count of 5048.

I executed both in anonymous apex, but map count giving a different result.

1 Answer 1


After investigation i found that i had duplicate accounts. Hence the different count in Map vs SOQL count.

A validation rule created at a later stage prevented more accounts to be inserted with the same name.

  • 2
    Yep, that'd do it. Calling .put() on a map and using the same key will overwrite the value for that key. The .put() method does return an Object, so you could detect this happening by doing something like Object result = myMap.put(key, value); followed by if(result != null){ system.debug('replaced value in map'); } (.put() returns the previous value for the key if the key already existed in the map)
    – Derek F
    Aug 1, 2023 at 0:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .