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

Posted on 09/17/2012, in No category and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: