Fundamentals
AMPscript is a server-side scripting language unique to Salesforce Marketing Cloud. It executes at render time — when an email is being prepared to send to each subscriber, or when a Cloud Page is loading. This means it can access and output subscriber-specific data for every individual in your send.
When to use AMPscript vs other tools
| Use case | Best tool |
|---|---|
| Simple personalisation (first name, etc.) | Personalisation strings %%FirstName%% |
| Show/hide blocks by attribute | Content Builder dynamic content rules |
| Look up data from another DE | AMPscript Lookup() |
| Loop through multiple rows (e.g. cart items) | AMPscript LookupRows() + FOR |
| Complex conditional logic with many branches | AMPscript IF/ELSEIF/ELSE |
| External HTTP call | SSJS (AMPscript cannot make HTTP requests) |
| Cloud Page form processing | AMPscript or SSJS |
Syntax rules
- AMPscript is case-insensitive —
IF,if, andIfall work - Variable names start with
@—@myVariable - Logic blocks are wrapped in
%%[ ]%% - Inline output uses
%%=v(@variable)=%% - Strings are wrapped in single quotes:
"hello" - Comments:
/* this is a comment */
In emails, AMPscript executes during the send process and cannot make HTTP calls. On Cloud Pages, AMPscript runs on page load and has access to URL parameters via RequestParameter(). Some functions (like UpsertDE()) are available in both contexts.
Variables & output
%%[
/* Declare one or multiple variables */
VAR @firstName, @lastName, @fullName
/* Set from subscriber attribute (sending DE field) */
SET @firstName = AttributeValue("FirstName")
SET @lastName = AttributeValue("LastName")
/* Combine into a third variable */
SET @fullName = Concat(@firstName, " ", @lastName)
]%%
<!-- Output inline -- use %%=v()=%% -->
<p>Hello, %%=v(@fullName)=%%!</p>
<!-- Setting a literal value -->
%%[ SET @brand = "Acme Corp" ]%%
<p>From: %%=v(@brand)=%%</p>
Conditionals
%%[
VAR @tier, @message
SET @tier = AttributeValue("LoyaltyTier")
IF @tier == "Gold" THEN
SET @message = "Enjoy your exclusive Gold member benefits."
ELSEIF @tier == "Silver" THEN
SET @message = "You're one step from Gold — here's how to get there."
ELSE
SET @message = "Join our loyalty programme to start earning rewards."
ENDIF
]%%
<p>%%=v(@message)=%%</p>
%%[ /* IIF(condition, value_if_true, value_if_false) */
VAR @salutation
SET @salutation = IIF(AttributeValue("Gender") == "Female", "Ms", "Mr")
]%%
<p>Dear %%=v(@salutation)=%% %%=v(AttributeValue("LastName"))=%%,</p>
%%[
VAR @name
SET @name = AttributeValue("FirstName")
/* If field is empty, use a fallback */
IF Empty(@name) THEN
SET @name = "there"
ENDIF
]%%
<p>Hey %%=v(@name)=%% 👋</p>
<!-- Renders "Hey there 👋" if FirstName is blank -->
String functions
%%[
VAR @str
/* Concat — join strings */
SET @str = Concat("Hello", " ", "World") /* "Hello World" */
/* Uppercase / Lowercase */
SET @str = UpperCase("hello") /* "HELLO" */
SET @str = LowerCase("WORLD") /* "world" */
SET @str = ProperCase("john smith") /* "John Smith" */
/* Length and trimming */
SET @str = Length("hello") /* 5 */
SET @str = Trim(" hello ") /* "hello" */
/* Substring */
SET @str = Substring("Hello World", 1, 5) /* "Hello" */
/* Replace */
SET @str = Replace("Hello World", "World", "SFMC") /* "Hello SFMC" */
/* Contains — returns 1 (true) or 0 (false) */
IF Contains(AttributeValue("EmailAddress"), "@gmail") THEN
/* subscriber is a Gmail user */
ENDIF
]%%
Date functions
%%[
VAR @now, @future, @diff, @formatted
/* Current date/time */
SET @now = Now()
SET @today = Now(1) /* date only, no time */
/* Add days to a date */
SET @future = DateAdd(@now, 7, "D") /* 7 days from now */
/* Difference between two dates */
SET @expiry = AttributeValue("OfferExpiry")
SET @diff = DateDiff(@now, @expiry, "D") /* days until expiry */
/* Format a date for display */
SET @formatted = FormatDate(@expiry, "MMMM d, yyyy") /* "June 15, 2026" */
SET @shortDate = FormatDate(@expiry, "dd/MM/yyyy") /* "15/06/2026" */
/* Extract date parts */
SET @year = DatePart(@now, "Y")
SET @month = DatePart(@now, "M")
SET @day = DatePart(@now, "D")
]%%
<p>Your offer expires %%=v(@formatted)=%% — only %%=v(@diff)=%% days left.</p>
Data lookups
%%[
/* Lookup(DE_Name, ReturnField, MatchField, MatchValue) */
VAR @subKey, @tier, @region
SET @subKey = AttributeValue("SubscriberKey")
/* Single field lookup */
SET @tier = Lookup("LoyaltyDE", "Tier", "SubscriberKey", @subKey)
SET @region = Lookup("ProfileDE", "Region", "SubscriberKey", @subKey)
/* Multi-key lookup (match on two fields) */
SET @price = Lookup("PricingDE",
"Price",
"Region", @region,
"Tier", @tier
)
]%%
%%[
VAR @subKey, @rows, @rowCount
SET @subKey = AttributeValue("SubscriberKey")
/* LookupOrderedRows(DE, MaxRows, OrderField, ASC/DESC, MatchField, MatchValue) */
SET @rows = LookupOrderedRows(
"RecentOrdersDE",
3, /* max 3 rows */
"OrderDate", "DESC", /* newest first */
"SubscriberKey", @subKey
)
SET @rowCount = RowCount(@rows)
]%%
%%[ IF @rowCount > 0 THEN ]%%
<h2>Your last %%=v(@rowCount)=%% orders</h2>
%%[ FOR @i = 1 TO @rowCount DO
SET @row = Row(@rows, @i)
SET @item = Field(@row, "ProductName")
SET @date = Field(@row, "OrderDate")
SET @date = FormatDate(@date, "d MMM yyyy")
]%%
<p>%%=v(@item)=%% — %%=v(@date)=%%</p>
%%[ NEXT @i ]%%
%%[ ENDIF ]%%
Loops
%%[
VAR @subKey, @rows, @rowCount, @i
VAR @row, @name, @price, @image, @url
SET @subKey = AttributeValue("SubscriberKey")
SET @rows = LookupRows("CartAbandonDE", "SubscriberKey", @subKey)
SET @rowCount = RowCount(@rows)
]%%
%%[ IF @rowCount > 0 THEN ]%%
<table width="600"><tr>
%%[
FOR @i = 1 TO @rowCount DO
SET @row = Row(@rows, @i)
SET @name = Field(@row, "ProductName")
SET @price = Field(@row, "Price")
SET @image = Field(@row, "ImageURL")
SET @url = Field(@row, "ProductURL")
]%%
<td style="padding:10px; text-align:center;">
<a href="%%=v(@url)=%%">
<img src="%%=v(@image)=%%" width="160" alt="%%=v(@name)=%%" />
</a>
<p><strong>%%=v(@name)=%%</strong></p>
<p>£%%=v(@price)=%%</p>
</td>
%%[ NEXT @i ]%%
</tr></table>
%%[ ELSE ]%%
<p>Your basket is ready when you are.</p>
%%[ ENDIF ]%%
Writing to Data Extensions
%%[
VAR @subKey, @email, @result
SET @subKey = AttributeValue("SubscriberKey")
SET @email = AttributeValue("EmailAddress")
/* UpsertDE — update if key exists, insert if not */
/* UpsertDE(DE_Name, KeyFieldCount, KeyField1, KeyValue1, ..., DataField1, DataValue1, ...) */
SET @result = UpsertDE(
"EmailOpensLog",
1,
"SubscriberKey", @subKey,
"EmailAddress", @email,
"LastOpenDate", Now()
)
/* InsertDE — add a new row (fails if key exists) */
SET @result = InsertDE(
"AuditLog",
"SubscriberKey", @subKey,
"EventType", "EmailOpen",
"EventDate", Now()
)
/* UpdateDE — update existing row, fail if not found */
SET @result = UpdateDE(
"Preferences",
1,
"SubscriberKey", @subKey,
"LastUpdated", Now()
)
/* DeleteDE — remove a row */
SET @result = DeleteDE(
"TempHoldDE",
1,
"SubscriberKey", @subKey
)
]%%
Snippet library
Ready-to-use patterns for common SFMC use cases. Copy and adapt for your sends.
Birthday email personalisation
%%[
VAR @dob, @dobMonth, @dobDay, @nowMonth, @nowDay
SET @dob = AttributeValue("DateOfBirth")
SET @dobMonth = DatePart(@dob, "M")
SET @dobDay = DatePart(@dob, "D")
SET @nowMonth = DatePart(Now(), "M")
SET @nowDay = DatePart(Now(), "D")
IF @dobMonth == @nowMonth AND @dobDay == @nowDay THEN
SET @isBirthday = 1
ELSE
SET @isBirthday = 0
ENDIF
]%%
%%[ IF @isBirthday == 1 THEN ]%%
<h1>Happy Birthday, %%=v(AttributeValue("FirstName"))=%%! 🎂</h1>
<p>Here's a special gift from us today only.</p>
%%[ ELSE ]%%
<h1>A little something for you</h1>
%%[ ENDIF ]%%
Redirect with tracking (Cloud Page)
%%[
VAR @subKey, @destination
SET @subKey = RequestParameter("sk")
SET @destination = RequestParameter("url")
/* Log the click */
SET @log = InsertDE(
"ClickTrackingDE",
"SubscriberKey", @subKey,
"Destination", @destination,
"ClickDate", Now()
)
/* Redirect to the destination */
Redirect(@destination)
]%%
Personalised subject line
%%[
/* Used in the Subject Line field of your email */
VAR @firstName, @numItems
SET @firstName = AttributeValue("FirstName")
SET @numItems = AttributeValue("CartItemCount")
IF Empty(@firstName) THEN
SET @firstName = "there"
ENDIF
]%%
/* In the Subject field, reference variables: */
%%=v(@firstName)=%%, you left %%=v(@numItems)=%% item(s) in your cart
/* Renders as: "Alex, you left 3 item(s) in your cart" */