1

I am working with creating an object, and i am having trouble recalling the syntax to create a new object if the query comes up with 0 results.

I saw it in documentation but can't seem to find it anymore.

EDIT:

My if statement is suppose to insert a dummy insert into a table but i get DML errors.

3 Answers 3

4

dphil's answer is quite right (upvoted), but he is also correct that a lot of clarity would be useful here.

If you just want to check for a value and then create an object off the back of that, it can be achieved more concisely with something like (taking dphils lead)

if([SELECT Name FROM Account WHERE Name = 'name'].size() == 0) {
    Account acc = new Account(Name = 'name');
    // insert acc; //etc.etc.
}
5
  • 2
    I suppose clarity of the question is they key here. My way will allow you to have access to the object afterwards, and your way(Simon's) just ensures that it exists.
    – dphil
    Feb 11, 2014 at 15:18
  • I concur. The asker may wish to augment their question :) Feb 11, 2014 at 15:19
  • This was what i was looking for great!
    – user5619
    Feb 11, 2014 at 15:33
  • Followup question i get DML errors with an insert at that point. Any idea what may be causing it
    – user5619
    Feb 11, 2014 at 15:41
  • That may be worthy of another question? What object are you inserting, where are you doing this (Apex class/Trigger etc.) and what the error message/debug logs say.. lots of possibilities there! Feb 11, 2014 at 15:42
2

You might need a little more clarity on your question....

List accs = [SELECT Name FROM Account WHERE Name = :someName LIMIT 1];
Account acc;
if (accs.size() > 0)
{
  acc = accs[0];
} else
{
  acc = new Account(Name = someName);
  //insert acc;//Did you want it created right away?
}
0

There's a million ways to do this, so here's another. Use try / catch exception handling instead of if / else and size checks.

Note, this solution will only work if you're expecting a single record back.

Account acct = null;
try{
    //The following will throw an exception if no accounts are found.
    acct = [Select Name From Account Where Id=:acct.Id];
}catch(QueryException e){
    acct = new Account(Name='I was just created, upsert me if you dare');
}

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.