Skip to main content

AMPscript - Day 3 - Conditional Statement & Control Flow

Basic IF-ELSE-ELSEIF-THEN-ENDIF:

Confluence Link: https://elearningit24.atlassian.net/wiki/external/MjhmNTRmOWIzNmUyNDVkMTgzN2MxNmFiZjk2MzExMjQ

Quick understanding of each Conditional Statements

  • IF: Starts the statement and checks the very first condition.
  • THEN: Defines the action or code block to run if the preceding IF condition is true.
  • ELSEIF: Tests additional, alternative conditions if all previous IF or ELSEIF conditions were false.
  • ELSE: A final "catch-all" block that runs only if none of the preceding IF or ELSEIF conditions were met.
  • ENDIF: Closes the entire conditional statement and allows the rest of the program to continue running
  • Conditional Flow: AMPscript conditional logic is used in Salesforce Marketing Cloud to control personalization, dynamic content, and decision-making inside Emails, CloudPages, and Journeys. AMPscript has only one core conditional statement:

    IF Statement: The IF statement checks a condition and executes code only if the condition evaluates to TRUE. %%[ IF Age >= 18 THEN SET @msg = "Eligible" ENDIF ]%%

    Points to Remember

    ✅ Always initialize variables before using them to avoid blank outputs.

    ✅ Use NOT EMPTY() checks when working with customer attributes that may contain NULL values.

    ✅ Implement fallback content for missing data such as names, locations, or demographic information.

    ✅ Use ELSEIF instead of deeply IF statements whenever possible for better readability and easier maintenance.

    ✅ Validate critical fields like Email Address, Mobile Number, and Customer ID before displaying content.

    ✅ Apply IF conditions for compliance requirements such as age restrictions, consent management, and opt-in preferences.

    ✅ Leverage IF logic to personalize:

    • Subject lines
    • Hero banners
    • CTAs
    • Discounts
    • Language preferences
    • Transactional messages

    ✅ Standardize data values (e.g., Country Codes, Loyalty Tiers) to prevent condition mismatches.

    ✅ Keep business logic simple and reusable to improve performance and reduce troubleshooting effort.

    ✅ Test all possible scenarios, including:

    • Valid data
    • Missing data
    • Unexpected values
    • Multiple condition matches

    Syntax: %%[ IF <condition> THEN <statement> ENDIF ]%%

    Flow Diagram:


    Sample DE for use case:





    To start, go to Email Studio> Create an Blank email template and Drag and drop HTML.

    Set Variable: As per my Sample DE, I've added the fields in the variable because throughout the use cases I will be using each variable.(Ensure the @, Comma and spelling along with the capitalization are all correct, otherwise it will throw error.

    1️⃣ Eligibility & Compliance Checks (Most Common)

    Used in

    • Age-based offers

    • Gambling / alcohol / finance compliance

    • COPPA / GDPR consent logic

    ⚠️ Real-time issue

    • Age may be NULL → condition fails silently
      👉 Always add fallback



    Workflow for Use Case 1:




    AMPscript Code:

    %%[VAR @Age]%%
    %%[Set @Age=AttributeValue("Age")]%%

    %%[IF NOT EMPTY(@Age) And Age>= 20 THEN]%%
    You can access this offer

    %%[ELSE]%%
    Offer Restricted

    %%[ENDIF]%%

    Output

    Offer Restricted

    You can access this offer


    2️⃣ Personalization (Content Display Control)

    🟢 Show different message blocks


    Workflow for Use Case 2:



    Used in

    • Dynamic banners

    • Email body personalization

    • Subject line logic


    Code:
    %%[VAR @Gender, @FirstName, @HeroImage, @Greeting]%% %%[ Set @Gender=AttributeValue("Gender") Set @FirstName=AttributeValue("FirstName") ]%% %%[ IF @Gender=="Male" THEN Set @HeroImage="https://image.s10.sfmc-content.com/lib/fe2f117170640578741179/m/1/8d9fcb06-57b2-4776-b5ec-6815307eb49b.png"]%% %%[ELSE]%% %%[Set @HeroImage="https://image.s10.sfmc-content.com/lib/fe2f117170640578741179/m/1/967f3c19-6add-44de-85b5-340870f88da6.png"]%% %%[ENDIF]%% %%[IF NOT EMPTY (@FirstName) THEN Set @Greeting = CONCAT("Hi ", @FirstName) ELSE Set @Greeting = "Hi there"]%% %%[ENDIF]%% <br> %%=v(@Greeting)=%%


    Customise Greeting as per the First Name, image as per the Gender

    Name is empty in "FirstName" Field, so it says "Hi there" here.


    3️⃣ Offer & Promotion Logic

    🟢 Loyalty-based discounts


    Used in

    • Coupons

    • Promo codes

    • Exclusive campaigns


    Workflow for Use case 3:


    Code:
    %%[
    VAR @LoyaltyTier, @FirstName SET @LoyaltyTier = AttributeValue("LoyaltyTier") Set @FirstName = AttributeValue ("FirstName") ]%% %%[ IF @LoyaltyTier == "Gold" THEN SET @Discount = "Your discount is 30%" ]%% %%[ ELSEIF @LoyaltyTier == "Silver" THEN SET @Discount = "Your discount is 20%" ]%% %%[ ELSE SET @Discount = "Your discount is 10%" ]%% %%[ ENDIF ]%% %%[IF NOT EMPTY (@FirstName) THEN Set @Greeting = CONCAT("Hi ", @FirstName) ELSE Set @Greeting = "Hi there"]%% %%[ENDIF]%% <br> %%=v(@Greeting)=%% <br> %%=v(@Discount)=%%

    Output:



    When loyalty Tier is not set in the DE records, it will automatically give the default 10% as per the AMPscript code:
    %%[
    ELSE SET @Discount = "Your discount is 10%" ]%%


    4️⃣ Localization / Language Handling

    Use cases

    • Multi-language emails

    • Country-specific legal footers

    • Regional content

    ⚠️ Production issue

    • Country codes mismatch (IN vs India)
      👉 Normalize data upstream


    %%[
    VAR @FirstName, @Language, @Country, @Greeting, @Message

    SET @FirstName=AttributeValue("FirstName")
    SET @Language=AttributeValue("Language")
    SET @Country=AttributeValue("Country")
    ]%%

    %%[
    IF @Country == "IN" OR @Country == "India" THEN
    SET @Language = "Hindi"
    SET @Message = "विशेष ऑफर केवल आपके लिए!"
    ELSEIF @Country == "FR" THEN
    SET @Language = "French"
    SET @Message = "Offre spéciale juste pour vous"
    Else 
    SET @Language = "English"
    SET @Message = "Special offer just for you!"
    ENDIF]%%

    %%[IF NOT EMPTY(@FirstName) THEN
    SET @Greeting = CONCAT("Hi ", @FirstName)
    ELSE
    SET @Greeting = "Hi There"
    ENDIF]%%

    %%=v(@Greeting)=%%<br>
    <br>
    %%=v(@Language)=%%<br>
    <br>
    %%=v(@Message)=%%

    Output:


    5️⃣ Channel Suppression (Email / SMS / Push)

    Use cases

    • CAN-SPAM compliance

    • Opt-in based channel control

    • Preference centers


    Important: AMPscript does not prevent an email from being sent. "True" channel suppression should be implemented using Journey Entry Criteria, SQL filters, Suppression Lists, or Exclusion Data Extensions before the send occurs.

    START
       │
       ▼
    Retrieve EmailOptIn
       │
       ▼
    EmailOptIn = True?
        │
     ┌---------I─────┐
     │          │
    YES        NO
     │          │
    ▼          ▼
    Show      Suppress
    Offer      Marketing Content
     │          │
     └────┬─────┘
          │
          ▼
     Render Email
          │
          ▼
          END


    Code:

    %%[ VAR @FirstName, @EmailOptIn, @Message, @Greeting SET @FirstName = AttributeValue("FirstName") SET @EmailOptIn = AttributeValue("EmailOptIn") ENDIF]%% %%[IF @EmailOptIn == "True" THEN SET @Message = "🎉 Exclusive 20% Discount Coupon" ELSE SET @Message = "Please update your communication preferences." ENDIF]%% %%[IF NOT EMPTY(@FirstName) THEN Set @Greeting = CONCAT("Hi ",@FirstName) ELSE SET @Greeting = "Hi There" ENDIF]%% %%=v(@Greeting)=%%<br> <br> %%=v(@Message)=%%


    Output: Email OptIn "True"

    Email OptIn "False"

    6️⃣ Dynamic CTA / URL Handling

    Used for

    • Mobile vs desktop experience

    • App deep links

    • Tracking URLs


    Code: (If you have CTA link existing in DE, you can use the below coding)

    %%[VAR @FirstName, @Device, @CTAURL, @CTAText, @Greeting SET @FirstName = AttributeValue("FirstName") SET @Device = AttributeValue("Device") SET @CTAURL = AttributeValue("CTAURL") ]%% %%[IF @Device == "Mobile" THEN SET @CTAText = "Shop on Mobile" ELSEIF @Device == "Desktop" THEN SET @CTAText = "Shop on Desktop" ELSE SET @CTAText = "Click Here" ENDIF]%% %%[IF NOT EMPTY(@FirstName) Then SET @Greeting = CONCAT("Hi ", @FirstName) ELSE @Greeting = "Hi There" ENDIF]%% %%=v(@Greeting)=%% %%=v(@CTAURL)=%% %%=v(@CTAText)=%%


    Code: (If you don't have CTA link existing in DE, you can use the below coding)
    %%[VAR @FirstName, @Device, @CTAURL, @CTAText, @Greeting SET @FirstName = AttributeValue("FirstName") SET @Device = AttributeValue("Device") SET @CTAURL = AttributeValue("CTAURL") ]%% %%[IF @Device == "Mobile" THEN SET @CTAText = "Shop on Mobile" SET @CTAURL = "https://m.company.com/sale" ELSEIF @Device == "Desktop" THEN SET @CTAText = "Shop on Desktop" SET @CTAURL = "https://m.company.com/sale" ELSE SET @CTAText = "Click Here" ENDIF]%% %%[IF NOT EMPTY(@FirstName) Then SET @Greeting = CONCAT("Hi ", @FirstName) ELSE @Greeting = "Hi There" ENDIF]%% %%=v(@Greeting)=%%<br> <br> <a href="%%=RedirectTo(@CTAURL)=%%"> Shop Now </a><br> <br> %%=v(@CTAText)=%%

    <a href="%%=RedirectTo(@CTAURL)=%%"> Shop Now: This code helps you add hyperlink


    7️⃣ Data Validation & Null Handling (CRITICAL)

    🟢 Prevent broken emails

    🟢 Default fallback values

    🔥 Most common real-world bug
    ➡️ AMPscript fails silently when values are NULL


    Code:

    %%[
    VAR @EmailAddress, @City, @Status, @FirstName

    SET @EmailAddress = AttributeValue("EmailAddress")
    SET @City = AttributeValue("City")
    SET @FirstName = AttributeValue("FirstName")

    /* 1. Prevent broken emails */

    IF EMPTY(@EmailAddress) THEN
        SET @Status = "Invalid Record"
    ENDIF

    /* 2. Default fallback values */

    IF EMPTY(@City) THEN
        SET @City = "Your Area"
    ENDIF
    ]%%

    %%=v(@FirstName)=%%<br>
    <br>
    %%=v(@Status)=%%<br>
    <br>
    %%=v(@City)=%%<br>
    <br>
    %%=v(@EmailAddress)=%%

    Output: 

    "Invalid Record" Email address:


    "Your Area" where the city was not mentioned

    8️⃣ Behavioral Targeting (Engagement Based)

    Use cases

    • Re-engagement campaigns

    • Win-back journeys

    • Content throttling


    Code:

    %%[VAR @LastOpenDays, @Segment SET @LastOpenDays = AttributeValue("LastOpenDays") IF @LastOpenDays <= 30 THEN SET @Segment = "Active" ELSE SET @Segment = "Inactive" ENDIF]%% %%=v(@LastOpenDays)=%% %%=v(@Segment)=%%

    Output:

    45 Days - Inactive

    15 Days - Active

    9️⃣ Transactional Emails (Order / Payment Logic)

    Used in

    • Order confirmation

    • Payment failure emails

    • Refund notifications


    Code:

    %%[VAR @FirstName, @OrderStatus, @Greeting, @msg

    SET @OrderStatus = AttributeValue("OrderStatus")
    SET @FirstName = AttributeValue("FirstName")

    IF OrderStatus == "Confirmed" THEN
      SET @msg = "Your order is confirmed"
    ELSEIF OrderStatus == "Cancelled" THEN
      SET @msg = "Your order was cancelled"
    ENDIF]%%

    %%[IF NOT EMPTY(@FirstName) Then 
    SET @Greeting = CONCAT("Hi ", @FirstName)
    ELSE @Greeting = "Hi There"
    ENDIF]%%

    %%=v(@Greeting)=%%<br>
    <br>
    %%=v(@msg)=%%

    Output:


    🔟 Journey Decision Pre-Processing

    Why used

    • Prepare flags before Journey entry

    • Reduce Decision Split complexity

    • Performance optimization


    Code:

    %%[VAR @CustomerScore, @Path, @SubscriberKey SET @CustomerScore = AttributeValue("CustomerScore") SET @SubscriberKey = AttributeValue("SubscriberKey") ]%% %%[IF @CustomerScore <= 80 THEN SET @path = "High Value" ELSE SET @Path = "Standard" ENDIF]%%

    Output:

    Customer score & path:



    This code is an automated classification engine. It evaluates your raw customer data and categorizes subscribers into tracks at the exact moment an email is generated. Instead of manually managing different lists, this script updates a hidden tracking flag (@Path) dynamically. You use that flag to:
    • Automatically show different layout designs to different tiers.
    • Segment users inside a Journey Builder Decision Split.
    • Clean up your database context before data goes to external systems

    Comments

    Popular posts from this blog

    A/B Testing

    Confluence link 1:  https://elearningit24.atlassian.net/wiki/external/MzA3YWUxNjI3YzBkNGZiZmFlZTc1ZGIzYmU1ZmM1MmQ   What is A/B Testing? A/B testing, also known as split testing , is a controlled experiment where two versions of a webpage, email, ad, or any digital asset are tested against each other to determine which one performs better. Why? Higher open rates Better Engagement Increased Sales and Lead conversion Reduced unsubscribed rates Date Driven- No assumption & Proven Results Test Type Subject Line Email Content Area From Name Send Date & Time Pre Header   Email Test Template: Friendly and Personalised Straight to the point & Action Oriented Confluence Link 2:  https://elearningit24.atlassian.net/wiki/external/NDk0Zjg0ODk3YjAwNDI5ZjkxOTVmMTAxNTQ3ZjlhNmQ Subject Line A/B Test: A/B Testing Use Case: Optimizing Email Subject Lines for Higher Open Rates Scenario- Subject Line: A company wants to increase the open rates of its promotional emails in Sa...

    Email Marketing Campaings

    Use Cases of Standard Data Extensions 1. Customer Data Storage Scenario : A retail business wants to store customer information, such as names, email addresses, and purchase history, for email marketing campaigns. Solution : Use a standard data extension to store and manage customer data securely and efficiently. Data Extension Structure Field Name Data Type Length Required Primary Key SubscriberKey Text 50 Yes Yes FirstName Text 50 Yes No LastName Text 50 Yes No EmailAddress EmailAddress N/A Yes No PurchaseHistory Decimal N/A No No Sample Records SubscriberKey FirstName LastName EmailAddress PurchaseHistory 001 John Doe john.doe@example.com 1500.50 002 Jane Smith jane.smith@example.com 200.00 https://mc.s8.exacttarget.com/cloud/#app/Email/C12/Default.aspx?entityType=none&entityID=0&ks=ks%23Subscribers

    SQl Query

      Workflow: Journey Builder> Automation Studio> New Automation Enter Query: Drag and drop Schedule in  Start with a Starting Source and the SQL Query> Choose Query> Create New Query Activity> Name your file and add your query (Field name thats part of the DE you create separately- Example: FirstName, LastName, Subscriber Key) Create a new DE in Email Studio with the query field> Select The test DE which was created: Select Target DE and Save & Run Workflow: Select All Activities and Run Workflow: Activity Details: Run Completed with updated DE Edit/ add another query: Copy Source DE and create a new DE with same fields that we are running in SQL: Run the updated SQL Query added Activity and DE updated with Records: Completed Status: Received error: When the Query field and the DE created field does not match When an existing Query is being run, if we try to run another query Fixed the error by matching same field Waiting for existing query to complete