+ Start a Discussion
mallikammallikam 

whats the difference?(question about triggers)

Following an example, I have written the following statement in my trigger after update which is activated when a child case is closed:

 

list<Case> a = [Select Id from Case where Id = :Trigger.New[0].ParentId and Subject = 'Delete Network ID or Reset password' limit 1];

if(a.size() != 0) { b = a[0];}

 

It works just fine! Then, I thought why cant I just have a single sboject instead of a list of sobjects and I changed the above to

the following:

 

Case a = [Select Id from Case where Id = :Trigger.New[0].ParentId and Subject = 'Delete Network ID or Reset password' limit 1];

 

This statement is throwing an exception when I try to close a child case if the parent objects subject is not a 'Delete Network ID or Reset password'.

 

System.QueryException: List has no rows for assignment to SObject

 

Why so? I did not understand exactly how a list is making the difference?

 

 

wesnoltewesnolte

Hey

 

If you assign the result of a query to a list and there are no matching rows it will simply return an empty list, whereas if you assign the same result to a single object it throws the exception you see. This is simply the way it's been built and can be quite confusing for developers that are new to the platform. There seems to be some debate as which one to use and when

 

If I was expecting a single record result I would probably use the second option and surround it with a try-catch block in case a query exception was thrown. 

 

Cheers,

Wes 

Message Edited by wesnolte on 07-27-2009 06:39 AM
mallikammallikam

Thanks!! That makes sense. :)