Basics of AMPScript in Salesforce Marketing Cloud

Learn the basics of AMPscript in Salesforce Marketing Cloud to create personalized, data-driven, and dynamic marketing campaigns that boost engagement.

By Sharan Kumar Mariappan
Assistant Software Developer

Basics of AMPScript in Salesforce Marketing Cloud

 

In the modern world; to improve the sales, audience engagement is the major key. Have you ever noticed the personalized emails based on your interest from any product sales that you are trying to purchase? How they are understanding your requirements? Are they mind readers? Are they magicians? No, They are marketers, who know AMPScript to send the customized and dynamic emails based on specific conditions. What is AMPScript actually? Am I pointing lots of questions to you? No worries let me explain you, what is AMPScript, AMPScript basic syntaxes, functions, uses and best practices in detail.

If you are aware of any programming language, then it is not a tough task to learn the AMPScript from scratch. Where to start learning AMPScript? Obviously, there are some trails from Salesforce that will help. But I can’t lie that you will learn everything in the blog. But I will try to summaries necessary contents to learn AMPScript from Scratch.  

Let’s get started.

What is AMPScript?

AMPScript - Advanced Marketing Platform Script is a Proprietary Scripting language used in the Marketing Cloud developed by Salesforce. It will help the marketers or marketing cloud specialists to create dynamic content for personalized communications for example emails, landing Pages, SMS messages and mobile push notifications. In general, based on the subscribers data for which we need to run the personalized email campaigns. For that, we need content to be specified and data driven content. The marketers will achieve this through AMPScript.

Why AMPScript?

  • To run data driven campaigns

  • To send the Personalized emails

  • To apply some condition Logics (loops and lookups)

  • To improve the audience engagement

AMPScript Fundamentals and Syntax

The syntax is more common like other programming languages. Usually other scripting language uses curly braces {}. AMPScript syntax uses two percentage signs (%%) and then followed by square brackets[].There are three basic types of AMPScript. They are

  • Inline AMPScript

  • AMPScript Blocks

  • AMPScript (SSJS) tag

Let see the examples of all the three in the below code block

/*  Inline AMPScript  */

%%=Output(Concat(@name, @i))=%%
/* AMPScript Block */

%%[ LOWERCASE(Name) ]%%
/* AMPScript SSJS script tag */

<script runat=server language=ampscript>
Lowercase(Name)
</script>

 

Creating Assigning Values to the Variable

In AMPscript, we use the ‘@’ symbol before a variable name to indicate that It is a variable. To assign a value to a variable, we use the SET keyword.

Unlike other scripting languages, AMPscript does not require the VAR keyword before using SET (That is data type of the variable). You can directly declare and assign values to variables using the SET keyword, as shown below.

%%[
  SET @firstName = "Sharan"     /* This an example for declaring and assigning value to variable named firstname */

]%%


Hello %%=v(@firstName)=%%  

We can also use VAR keyword to declare a variable explicitly and it is completely optional.

%%[
  VAR @firstname, @city         /* Explicitly declare a variable */
  SET @firstName = "Sharan"
  SET @city ="Pollachi"   
]%%


Hello %%=v(@firstName)=%%

 

IF-ELSE Statements

AMPScript uses the IF ELSE statement like other scripting languages. Such as IF, ELSEIF, ELSE and ENDIF.

  • IF -  checks the first condition.
  • ELSEIF - checks next condition, if the first one is false.
  • ELSE - runs, if none of the above conditions are true.
  • ENDIF - closes the conditional block.

See the example we have declared a variable named CityType and in the if condition, I have added the condition. If the CityType is equal to "Urban", then print the message as "Plant more trees please", If the CityType is equal to Rural then print the message as "Save Soil". Otherwise print the message as "Don't use plastics please..".

%%[

  SET @CityType= "Urban"
  
  IF @CityType== "Urban" THEN
    SET @message = "Plant more trees please"
  ELSEIF @CityType== "Rural" THEN
    SET @message = "Save soil"
  ELSE
    SET @message = "Don't use plastics please..."
  ENDIF
]%%

<p>%%=v(@message)=%%</p>

 

Inline IF statement

Please see the syntax for inline if statement below

IIF(condition, valueIfTrue, valueIfFalse)
  • IIF(condition, value_if_true, value_if_false) is a shortcut for IF...ELSE.
  • It evaluates the condition and returns the appropriate value.
  • Exactly like Excel’s IF function.
%%[
SET @firstName = "Apple"
SET @greeting = IIF(@firstName == "Apple", "Hi", "Hello")
]%%

%%=v(@greeting)=%%

 

Loops in AMPScript

We can implement loops in AMPScript to iterate over content as many time based on the requirement. Let’s assume we need to print the name for 10 times we can achieve it using two formats 

%%[FOR @i=1  TO 10 THEN DO]%% 

Trial loop 

%%[NEXT @i]%%  /* Format 1 */
%%[ FOR @i =1 TO 10 DO]%% 

OutputLine(Concat(Trial Loop, @i)) 

]%%  /* Format 2 */

 

Lookup Functions

Lookup functions in AMPScript will help to retrieve data from the Data Extension during sending the emails. There are some common lookup functions in AMPScript,

  • Lookup() - help to retrieve sing value from the data extension
  • LookupRows() - Retrieve all rows that match filter criteria
  • RowCount() - Returns the number of rows returned by LookupRows()
  • Row() - Retrieve a specific row from a set of rows
  • Field() - Retrieve a field value from a specific row
Lookup()

Returns specified values from a data extension. We can pass four different ordinals to the lookup function whose syntax is shown below.

Lookup(1,2,3,4..)
  1. Name of the data extension
  2. Name of column from which to return a value
  3. Name of column from which to return a value
  4. Value to match string against
%%=Lookup('EventData','Name','Region','Adland')=%%

Link for data extension used in the above example, try to test by yourself: https://github.com/camrobert/SFMC-with-me/blob/main/001-Dynamic%20Content%20Blocks/EventData.csv

LookupRows()

Retrieve and returns the specified row based on the given criteria. Lookup rows are even classified into three types:

  • LookupRowsCS() - This is used for case sensitive function to retrieve the rows based on the condition
  • LookupOrderedRows() - It will allows you to specify a column and direction of sort the rowset by criteria
  • LookupOrderedRowsCS() - Case sensitive version of LookupOrderedRows() function

Let see the examples for all the lookup row function.

When order of the results are not important, then we use LookupRows() function

LookupRows(1,2,3,4..)
  1. Name of the data extension
  2. Name of the column from which to return a value
  3. Name of the value in the column (2) to retrieve the rows
  4. We can add the next condition (like 2 and 3). multiple conditions can be added that acts as AND condition in the function. Let me show you the example.
%%=LookupRows('EventData','Region','Adland')=%%

Let see the example for LookupRows(). In this example, I have created a variable @abc and stored the LookupRows(), I have added the data extension name as EventData, column name as region and condition for that column should be Adland. Then, I have counted the number of rows which matches the criteria and stored it in the variable named @abcRowCount. I have included FOR loop starting from 1 to the row count that stored in the @abcRowCount variable. Then, we have set to perform the operations inside FOR loop. Inside the for loop. I have set new variable and stored the row value using Row() function. Also, I have set the new variable to store the Field values using FIELD() function. Let we see more about ROW() and FIELD() functions later in detail.

Code

%%[

SET @abc=LookupRows('EventData','Region','Adland')

SET @abcRowCount=RowCount(@abc)

FOR @j=1 TO @abcRowCount DO

SET @abcRow = Row(@abc, @j)

SET @EventName = Field(@abcRow,"Name")

]%%

<p>%%=v(@EventName)=%%</p>

%%[NEXT @j
]%%

Output

InteractiveAds Summit

ContentCreators Showcase

VideoMarketing Expo

PodcastMarketing Expo
 
LookupRowsCS()

If, we change region name as adland instead Adland. This will be not work, since we applied case sensitive inside that.

LookupOrderedRows()
LookupOrderedRows(1,2,3,4,5,[6a,6b]...)
  1. Name of the data extension from which to return rows.
  2. Number of rows to return. Specifying 0 or -1 will return all matching rows. (Note: As per the documentation maximum number of rows returned is 2,000).
  3. We can add ASC or DESC to specify whether to display ascending or descending
  4. Name of the column that identifies the rows to retrieve
  5. Values that identifies the rows to retrieve
  6. Additional column to specify additional conditions (6a and 6b).

Code

%%[
SET @rows = LookupOrderedRows('EventData',3,'Date ASC','Region',region)
FOR @k=1 TO RowCount(@rows) DO
SET @value=ROW(@rows, @k)
SET @value1=FIELD(@value,'Name')
]%%

<p>%%=v(@value1)=%%</p>

%%[
NEXT @k
]%%

Output

DigitalMarketing Summit 2024

RetailRevolution Expo

SocialMedia Expo 2024

Note: Use the same data extension that we used above to practice from your end. 

LookupOrderedRowsCS()

The same syntax but case sensitive when we change the code Region instead region will not produce an output.

RowCount()

RowCount() function will return the number of rows that present in the variable. The row is created based on the specified conditions and then stored inside the variable.Please refer the code below. In the third line of the code will specify the number of rows that present in the variable @rows. In this example the row count is 4 (please refer the data extension used earlier). The RowCount() function has one parameter, rowset (string): that is required and the rowset or array to find the number of rows for. Please refer the syntax below.

RowCount(rowset)
%%[
SET @rows = LookupOrderedRows('EventData',3,'Date ASC','Region',region)
FOR @k=1 TO RowCount(@rows) DO
SET @value=ROW(@rows, @k)
SET @value1=FIELD(@value,'Name')
]%%

<p>%%=v(@value1)=%%</p>

%%[
NEXT @k
]%%
 
ROW()

ROW() function will returns the specific row from the row set or an array. When we are storing the row set inside the variable @abc from the above example. Then, we are retrieving the rows from the row set using ROW() function. Let say for example, we want to retrieve 1 to 4 rows from the row set, we will include row position from 1 to 4 in the iteration.

Row(rowset, rowPosition)
/* Example */

SET @value=ROW(@rows, @k)
 
FIELD()

Usually field and row is used as a combination to display the specific field from the row. Row that is fetched from rowset using the ROW() function and the field that is retrieved based on the specific column name. Let see the syntax and example for the FIELD() function below.

The Field() function has three parameters:

  • row (string): Required. The row object that contains the field that you want to return. 

  • fieldName (string): Required. The name of the field to return from the row.

  • boolExceptionIfNotFound (boolean): If true, the function returns an exception if the specified field doesn’t exist. If false, the function returns an empty string if the field doesn’t exist. The default value is true.

/* Syntax */

Field(row, fieldName, boolExceptionIfNotFound)
/* Example */

SET @value=ROW(@rows, @k)
SET @value1=FIELD(@value,'Name')
 
Math() Functions

The math function will allows you to perform numerical calculations, rounding off the values, comparisons, and random number generations.

  • Add(a,b) ->  Adds two numbers
  • Subtract(a,b) -> Subtracts second number from the first number
  • Multiplication(a,b) -> Multiplies two numbers
  • Divide(a,b) -> Divide first number by second number
  • Mod(a,b) -> Returns remainder after division
  • Round(number, decimals)
  • Ceiling(number)
  • Floor(number)
  • Abs(number)
  • Random(min, max)
  • Min(x,y)
  • Max(x,y)

Code

%%[
  SET @add = Add(10, 2)
  SET @subtract = Subtract(10, 2)
  SET @multiply = Multiply(10, 2)
  SET @divide = Divide(10, 2)
  SET @mod = Mod(10, 2)


  SET @round = Round(3.14159, 2)
  SET @ceiling = Ceiling(3.2)
  SET @floor = Floor(3.9)
  SET @abs = Abs(-5)


  SET @max = Max(10, 2)
  SET @min = Min(10, 2)


  SET @random = Random(1, 100)
  ]%%
  
  Addition: %%=v(@add)=%%
  Substract: %%=v(@subtract)=%%
  Multiplication: %%=v(@multiply)=%%
  Divide: %%=v(@divide)=%%
  Module: %%=v(@mod)=%%
  Round off Value: %%=v(@round)=%%
  Ceiling: %%=v(@ceiling)=%%
  Floor Value: %%=v(@floor)=%%
  Absolute value: %%=v(@abs)=%%
  Maximum: %%=v(@max)=%%
  Minimum: %%=v(@min)=%%
  Random number: %%=v(@random)=%%

Output

Addition: 12
Subtraction: 8
Multiplication: 20
Division: 5
Modulo: 0

Round-off Value: 3.14
Ceiling: 4
Floor Value: 3
Absolute Value: 5

Maximum: 10
Minimum: 2
Random Number: 3 (varies each time)

Best Practices

  • Always preview and test before sending.
  • Use clear variable names and add comments for complex logics.
  • Validate syntax before the preview.
  • Always include default values in case of data is missing (fallbacks).

Conclusion

I hope this blog helps you to learn the basic syntaxes and descriptions for the required basic functions in the AMPScript. In the upcoming blog let we explore the advanced concepts in the AMPScript in details. Follow our blogs for more updates.

 

 


free-consultation