Skip to main content

AMPscript Day 4 - Statement IIF() Function Guide

 Salesforce Marketing Cloud (SFMC) - IIF() Function Guide


What is IIF()?

IIF() is a shorthand AMPscript conditional function used to return one value when a condition is true and another value when false. Syntax: IIF(condition, value_if_true, value_if_false)


Use case to perform:

Use Case 1: Personalized Greeting IIF(Gender == "Male","Mr.","Ms.") 

Use Case 2: Loyalty Member Classification IIF(MemberStatus == "Gold","Premium Benefits","Standard Benefits") 

Use Case 3: Dynamic Discount Assignment IIF(TotalPurchase > 10000,"20% OFF","10% OFF") 

Use Case 4: Age Verification IIF(Age >= 18,"Adult","Minor") 

Use Case 5: Cart Abandonment Journey IIF(IsCartAbandoned == "True","Complete Your Purchase Today","Thank You For Shopping") 

Use Case 6: Mobile App Adoption IIF(IsAppUser == "Yes","Open App","Download App") 

Use Case 7: Lead Scoring IIF(LeadScore > 80,"Hot Lead","Cold Lead") 

Use Case 8: Dynamic Subject Line IIF(OpenCount > 5,"We Miss You Less!","We Miss You!") 

Use Case 9: Membership Discount Nested IIF for Gold/Silver/Bronze discounts


Data Extension: This DE stores input attributes (customer/lead data) for personalization, segmentation, and dynamic messaging.


>Now that we have a DE, will proceed to Email Studio> Create new content and select a black template> Drag and drop HTML.

Flow Diagram:



Code:

%%[

/*Declare All Variables*/

VAR @Gender, @Greeting, @MemberStatus, @Benifits, @TotalPurchase, @Discount, @Age, @Classification, @IsCartAbandoned, @SubjectLine, @IsAppUser, @OpenCTA, @LeadScore, @LeadStatus, @OpenCount, @DynamicSubject, @Tier, @NestedDiscount

/*Declare values from Attribute*/

SET @Gender = AttributeValue("Gender")
SET @MemberStatus = AttributeValue("MemberStatus")
SET @TotalPurchase = AttributeValue("TotalPurchase")
SET @Age = AttributeValue("Age")
SET @IsCartAbandoned = AttributeValue("IsCartAbandoned")
SET @IsAppUser = AttributeValue("IsAppUser")
SET @LeadScore = AttributeValue("LeadScore")
SET @OpenCount = AttributeValue("OpenCount")
SET @Tier = AttributeValue("Tier")


/*Apply Logic*/

/* Use Case 1: Greeting */


SET @Greeting = IIF(@Gender == "Male", "Mr.", "Ms.")


/* Use Case 2: Loyalty */

SET @BenefitsTier = IIF(@MemberStatus == "Gold", "Premium Benefits", "Standard Benefits")


/* Use Case 3: Discount */

SET @Discount = IIF(@TotalPurchase > 10000, "20% OFF", "10% OFF")


/* Use Case 4: Age Verification */

SET @Classification = IIF(@Age >= 18, "Adult", "Minor")


/* Use Case 5: Cart Abandonment */

SET @SubjectLine = IIF(@IsCartAbandoned == "True" OR @IsCartAbandoned == true, "Complete Your Purchase Today", "Thank You For Shopping")


/* Use Case 6: App Adoption */

SET @AppCTA = IIF(@IsAppUser == "Yes", "Open App", "Download App")


/* Use Case 7: Lead Scoring */

SET @LeadStatus = IIF(@LeadScore > 80, "Hot Lead", "Cold Lead")


/* Use Case 8: Dynamic Subject Line */

SET @DynamicSubject = IIF(@OpenCount > 5, "We Miss You Less!", "We Miss You!")


/* Use Case 9: Nested Membership Discount */

SET @NestedDiscount = IIF(@Tier == "Gold", "30% OFF", IIF(@Tier == "Silver", "20% OFF", "10% OFF"))

]%%

Render Email: %%=v(@Greetings)=%%<br>

%%=v(@Benifits)=%%<br>

%%=v(@Discount)=%%<br>

%%=v(@Classification)=%%<br>

%%=v(@OpenCTA)=%%<br>

%%=v(@LeadStatus)=%%<br>

%%=v(@DynamicSubject)=%%<br>

%%=v(@NestedDiscount)=%%<br>

Output:





*Numeric Fields: Do not wrap numeric values in quotes when running mathematical comparisons (e.g., > 10000 or >= 18), as quotes force the compiler to treat them as text, breaking mathematical evaluations.

*A salutation is a formal greeting used at the very beginning of a letter, email, or official message. It is the direct way you address the person you are writing to before diving into the main content

*A nested discount is a conditional logic structure where one IIF() statement is placed inside another IIF() statement.
Instead of evaluating only two options (True or False), a nested structure allows your code to evaluate multiple conditions in sequence until it finds a match.
Avoid nesting IIF() deeper than 3 levels (e.g., Gold ➡️ Silver ➡️ Bronze ➡️ Baseline).

Q&A
Q: What happens in Use Case 1 if a subscriber's Gender field is completely blank?
  • Answer: The current expression IIF(@Gender == "Male", "Mr.", "Ms.") will check if it equals "Male". Since a blank/null value does not match "Male", the condition falls through to the false branch and outputs "Ms."The Fix: To avoid misgendering blank records, wrap it in a data check to supply a neutral fallback: SET @Salutation= IIF(Empty(@Gender), "Customer", IIF(@Gender == "Male", "Mr.", "Ms."))
Q: In Use Case 5, what happens if IsCartAbandoned contains invalid text strings instead of a boolean value?
  • Answer: If the data syncing from your web platform contains mixed text strings (such as "yes", "y", or "1"), the rigid boolean script IIF(@IsCartAbandoned == "True" OR @IsCartAbandoned == true...) will fail and default to the "Thank You For Shopping" message. The Fix: Expand the boolean safety logic to catch alternative indicators: SET @SubjectLine = IIF(@IsCartAbandoned == "True" OR @IsCartAbandoned == true OR @IsCartAbandoned == "Yes", "Complete Your Purchase Today", "Thank You For Shopping")
Q: Why are we declaring all 9 use cases inside a single block at the top of the email instead of calculating them inline as they appear?
  • Answer: Placing calculation scripts scattered inside HTML structure forces the Salesforce Marketing Cloud parser engine to repeatedly pause, execute script logic, and resume rendering layout cells. Wrapping code elements inside a unified initialization block speeds up processing times, reduces server timeouts on massive sends, and makes your email architecture much easier to debug.

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