+ Start a Discussion
adrisseladrissel 

SOQL Query for Contacts with no Accounts

Hey all,

I am trying to perform a SOQL query in my controller to pull all Contacts in my org that have no associated AccountId.  Somehow some of my users, without access to the API, were able to create orphaned Contacts (Contacts without an Account selected upon creation).  This is breaking some custom Apex/VF we have programmed because of various Exceptions including "de-reference null object", et al.

I tried searching the web for some answer to this, but couldn't come up with anything.  When I perform the SOQL query it returns no information.  As soon as I add an account to the Contact in question it pulls perfectly with the query.

Can anyone tell me if what I am trying to do is even possible?  Is there a restriction with SOQL that only allows Contacts to be pulled IF they have an Account associated with them?  Is there any viable workaround?

Thanks!

Adam
 
Sagar PareekSagar Pareek
Hi Adam,

Can you please post your code here ?
adrisseladrissel
conNames = [SELECT Name,Id FROM Contact WHERE Id =: '00319000003KKwc'];
"00319000003KKwc" is the Id of the Contact that has no Account associated with it.

Thanks!
 
Sagar PareekSagar Pareek
Hi Adam,

Based upon your question 

"Somehow some of my users, without access to the API, were able to create orphaned Contacts (Contacts without an Account selected upon creation). "

You need to create a validation rule or make account field on contact required on page layout so that users cannot create orphaned contacts.

Or you will need to modify your controller where 

query will look like 
 
conName =[select name,id from contact where accountId!=null]

 
adrisseladrissel
I will deal with the validation separately.  What I am trying to do here, though, is program a "catch" in the controller in case it does happen again.  When I perform the SOQL query I displayed it returns nothing.  But, there is a Contact in my org with that Id.  I'm thinking SOQL just doesn't pull Contacts that aren't associated with an Account.

Can you confirm/deny that thought?

Thanks!

PS - Your query suggestion wouldn't work because I need to pull the opposite, where accountId = null