Conditional Statements in Salesforce Apex (Complete Guide with Examples)

In Salesforce Apex, conditional statements are among the most important programming concepts. These statements help developers control how code behaves under specific conditions.

In real-world Salesforce projects, we often need to make decisions. For example:

  • Give a discount based on the amount
  • Send email only if the status is “Closed Won.”
  • Execute logic only for specific users

Without conditional statements, your program will execute every line of code without any control. That’s why conditional statements are very important in Apex.

In Salesforce Apex, conditional statements are very useful for making decisions based on specific conditions.

For example, a company wants to give discounts to customers based on their purchase amount. As a Salesforce developer, I write an Apex if-else statement to check the customer’s purchase amount.

  • If the purchase exceeds $50,000, the customer receives a 20% discount.
  • If the purchase is between $20,000 and $50,000, the customer gets a 10% discount.
  • Otherwise, no discount is applied.

In this article, we will learn about conditional statements in Salesforce Apex. In this, I will explain If-Else, Nested If, and Switch Case statements, their syntax, and provide examples to use in Salesforce Apex code.

What are Conditional Statements in Salesforce Apex?

Conditional statements in Salesforce Apex are used to make decisions in code, allowing developers to execute specific actions only when certain conditions are met.

Logic control in Salesforce Apex includes conditional statements that help manage execution flow based on specific conditions

Types of Conditional Statements in Apex

The most common conditional statements are:

  1. If Statement
  2. If-Else Statement
  3. Else-If Statement / Nested If-Else Statement
  4. Switch Statement

In the following steps, I will explain these logical statements using examples.

1. If Statement in Salesforce Apex

The if conditions in Apex are similar to those in other programming languages. The if statement checks the specified condition and executes a block of code if it is true.

Syntax: Declare an If Statement in Salesforce Apex

if ( Condition ){
   //logic;
}

For example, we want to develop Apex code to display the number of records for any particular user with an opportunity stage name of ‘closed won’.

Here, I created a list collection to store opportunity records that we retrieved using a SOQL query. Now, using an if condition, we will check whether any record is available in the list.

If a record is available, execute the if block, which returns the record count stored in the declared integer variable.

public class Demo {
    
    public void IfConditionDemo() {

        Id ownerId = '0055i000004xf7XAAQ';
        List<Opportunity> oppList = [SELECT Id, StageName  FROM Opportunity WHERE OwnerId = :ownerId  AND StageName = 'Closed Won'];

        if ( !oppList.isEmpty() ) {
            Integer oppoCount = oppList.size(); 
            System.debug( 'Total number of "Closed Won" Opportunities: ' + oppoCount );
        }
    }
}
Conditional Statements in Salesforce Apex

In this way, we can use the if conditional statement in Salesforce Apex to execute the if block when the declared condition is true.

2. If-Else Statement in Salesforce Apex

In Salesforce Apex, the if-else statement executes specific blocks of code depending on whether a condition evaluates to true or false.

  • This allows your code to make decisions and perform actions based on the logic you define.
  • If the condition in the if block is true, that block of code will execute.
  • If the condition is false, the else block will execute instead.
  • Since the else block has no condition, it always runs when the if block does not.

Syntax: Declare an If-Else Statement in Salesforce Apex

if ( Condition ){
   // true codition;
}
else{
   // false codition; 
}

Here, we will use the same example, but this time, after fetching a record using SOQL, no record will be available in the list. That means the condition in the if block evaluates to false.

Then, if the if block is not executed, the else block is executed in the above Apex code.

// In the list there is no any record available.
 
if ( !oppList.isEmpty() ) {
            Integer oppoCount = oppList.size(); 
            System.debug( 'Total number of "Closed Won" Opportunities: ' + oppoCount );
        }
else{
         System.debug( ' There is no any record avaible in the List' );
      }
If Else Statement in Salesforce Apex

In this way, we can use the if-else conditional statement in Salesforce Apex to execute the else block when the if block condition is false.

3. Else-If Statement / Nested If-Else Statement in Salesforce Apex

The Else-If statement is not a standalone concept; however, when we have multiple conditions to check for truth or falsity, we need to add them using the Else-If statement, which is also known as the nested If-Else statement in Salesforce Apex.

Syntax: Else-If Statement / Nested If-Else Statement in Salesforce Apex

if (condition1) {    
     // execute if condition1 is true;
} else if (condition2) {    
     // Execute condition2;
} else if (condition3) {    
     // Execute condition3;
} else {   
     // code to be executed if all conditions are false;
}

For example, you have three integers and want to find the smallest no from those integers. Here, I declared three integers, then used if-else if statements to determine which number was the smallest and display the result accordingly.

        Integer x=20, y=30, z=10;
        if ( x<y && x<z ) {
            System.debug( 'Smallest No is X : '+x );
        }
        else if ( y<x && y<z ) {
            System.debug( 'Smallest No is Y : '+y );
        }
        else {
            System.debug ( 'Smallest No is Z : '+z );  
        }                      
Else if Statement in Salesforce Apex

4. Switch Statement in Salesforce Apex

The switch statement is used when we need to compare a variable against multiple potential values. It’s more efficient and easier to read than using multiple if-else conditions.

Syntax: Switch Statement in Salesforce Apex

switch on variable {    
         when value1 {        
               // execute if variable equals value1;    
           }    when value2 {        
             // execute if variable equals value1; 
           }   when else {        
            // code to be executed if variable doesn’t match any value;    
          }    
}

For example, we want to display the message based on the opportunity stages. Here, I declare the string data type as ‘stage’ and assign it the value ‘Closed Won’.

Then, the switch on stage is a conditional statement that decides on which basis the logic will be executed. We have assigned a value to the stage, and according to that value, the switch block will execute.

Now, execute the apex code below to see the output.

public class SwitchDemo {
    
    public void SwitchMethod() { 
        
    String stage = 'Closed Won';

        switch on stage {
            when 'Prospecting' {
                System.debug ( 'Initial Stage' );
            }
            when 'Closed Won' {
                System.debug ( 'Won the Opportunity' );
            }
            when else {
                System.debug ( 'Other Stage' );
            }
      }
   }
}

In the switch statement, we assigned the closed won value to the stage. According to that value, you can see the closed won block executed with the message we provided in the debug method.

Switch Statement in Salesforce Apex

Comparison of Conditional Statements

FeatureIfIf-ElseElse-IfSwitch
ConditionsSingleSingleMultipleMultiple
ReadabilityMediumGoodComplexBest
Use CaseSimple checkTwo conditionsMany conditionsFixed values
PerformanceFastFastSlower (many checks)Faster

Frequently Asked Questions

1. What is a conditional statement in Apex?

A conditional statement is used to make decisions in code. It executes a block only when a condition is true.

2. What is the difference between if and switch?

If checks conditions one by one, while a switch compares a variable with multiple values and is more readable.

3. When should we use switch instead of if?

Use a switch when comparing one variable to many fixed values.

4. What is nested if?

Nested if means using multiple if conditions inside each other to handle complex logic.

5. Is the ternary operator better than if-else?

Ternary is shorter but should be used only for simple conditions.

Conclusion

I hope you have a good idea of conditional statements in Salesforce Apex. They allow your code to make decisions and take actions based on specific conditions.

Using If-Else, Nested If, and Switch Case statements, you can control the flow of your code. Conditional statements are very useful for automating business logic such as discounts, notifications, or validations.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.