function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

Find contacts without and related objects

How to find contacts which do not have cases, opportunities, activities, etc so that we can delete such contacts from the database? 
Thanks in advance.

Yogesh

 
krisstannum1krisstannum1
Query all contacts associated to each object:

EX:
SELECT CaseNumber,ContactId FROM Case WHERE ContactId != NULL
SELECT ContactId,Id FROM OpportunityContactRole WHERE ContactId !=NULL

Then collect all the contact id's from above queries and Query from contact all records that are NOT IN the above results
SELECT Id FROM Contact WHERE Id NOT IN : <list of ids collected from above>
DELETE above resulting list



 
GhanshyamChoudhariGhanshyamChoudhari
Hi,
 
List <contact> cons = [Select Id, (select id from cases where id=null),
(Select Id from opportunities where id = null),
(Select Id from tasks where id = null),
(Select Id from events where id = null)
from contact];

delete cons;



Mark as best answer if it helps you.
Thanks,
Ghanshyam Choudhari
Yogesh BiyaniYogesh Biyani
@Ghanshyan, the query seems to return all my contacts in the database. 

@krisstannum1, Is there an easier way to put this in one query because I want to use the dataloader to archive the contacts. 

BTW, Is there a way to know which objects have the lookups to contact 

So far, I have found following objects in our instance

Events
Quotes
Lead 
CampaignMember
Case
ZendeskSupportTicket
GhanshyamChoudhariGhanshyamChoudhari
setup>schema builder > clear all> select contact object