Use of IN operator in Salesforce SOQL

Use of IN operator in Salesforce SOQL

IN operator in Salesforce SOQL is used to include multiple filter values.

Sample SOQL:

SELECT Name 
FROM Account 
WHERE ID IN (
'0013t00002XXRyDAAX',
'0013t00002a6aT9AAI' ,
'0013t00002a6aTEAAY' 
)

Sample Code:

Set < Id > AcctIds = new Set < Id >();
AcctIds.add( '001U000000doU9v' );
AcctIds.add( '001U000000doU9w' );
AcctIds.add( '001U000000doU9x' );
AcctIds.add( '001U000000doU9y' );
AcctIds.add( '001U000000doU9z' );
String SOQL = 'SELECT Name FROM Account WHERE ID IN : AcctIds';
List < Account > Acct = Database.query( SOQL );

Example:

Visualforce page:

<apex:page controller="Sample" showheader="true">
    <apex:pageBlock >
        <apex:pageblockTable value="{!Acct}" var="A">
            <apex:column value="{!A.Name}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:page>

Apex Controller:

public class Sample
{   
    Set<ID> AcctIds = new Set<ID>();
    public List<Account> Acct {get;set;}
   
    public Sample() {       
        AcctIds.add('001U000000doU9v');
        AcctIds.add('001U000000doTbx');
        AcctIds.add('001U0000002LIXQ');
       
        String SOQL = 'SELECT Name FROM Account WHERE ID IN : AcctIds';
        Acct = Database.query(SOQL);
    }
}

Output:

Leave a Reply