Blog Archives

EXISTS clause in SOQL

Here is how to emulate the EXISTS clause in SOQL

In the example below Education__c is a custom object that has a lookup field to Contact.

Suppose you have a query that would be written like this:

SELECT Id, Name
FROM Contact cn
WHERE EXISTS (

SELECT 1
FROM Education__c
WHERE Contact__c =  cn.Id ) 

It can be rewritten in SOQL using an Id Semi-Join as:

SELECT Id, Name
FROM Contact cn 
WHERE Id IN (

SELECT Contact__c

FROM Education__c )

It will retrieve all Contacts that have an associated Education__c record.

It is possible to use up to 2 Id Semi-Joins in a SOQL query (more information about it).

 

Advertisements