Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some logic where I need to iterate thru a bunch of Opportunities. I need to be able to determine when I hit a new Opportunity Owner ID.

I try:

String lastownerId = '';

for (Opportunity opportunity: opportunities) {
    if(opportunity.OwnerId == (lastownerId)) {

I get: System.StringException: Invalid id:

any tips?

share|improve this question
up vote 8 down vote accepted

Salesforce has an ID-type, so you could use Id lastownerId = null; instead. This has the big advantage of being 15/18 character id insensitive in comparison, using string type may get you false negatives depending on what the input-id's look like.

Right now, you're apparently comparing some non-id string with an id. You will definitely get the error you see if you compare for example "apples" with an actual id, right now you're comparing it to an empty string which is also an invalid id. Comparing a valid id to null will not generate an error and result in False being returned as you might expect.

share|improve this answer
Completely agree with this. I ran into an issue the other day where I had a Custom Setting with a string type for ID. The issue ended up being comparing an 18-digit Id with a 15-digit one like Martin describes. Definitely use the Id type whenever you can. – James Loghry Jan 2 '13 at 21:31

Here you are comparing ID data type(opportunity.OwnerId) with String data type(lastownerId) value thats why you are getting this error.

There are 2 possible solutions -

1) either change lastownerId data type to Id like - 
       Id lastownerId = null;

2) OR convert opportunity.OwnerId to string first then compare;
share|improve this answer

You can't convert an empty String to an Id so the if-condition fails on first execution. Try changing the variable declaration to

Id lastOwnerId = null;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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