Salesforce Marketing Cloud Developer Reference

AMPscript Functions Reference

AMPscript is Salesforce Marketing Cloud’s proprietary server-side scripting language for personalizing HTML emails, SMS messages, push notifications, and CloudPages. Functions execute on SFMC servers before message delivery to retrieve subscriber attributes, query relational Data Extensions, format dates and currencies, and control dynamic layout rendering.

1. Multi-Line Code Block %%[ ... ]%%

Used for declaring variables (VAR), assigning values (SET), invoking functions (LookupRows()), and running IF / FOR control statements without printing direct HTML.

2. Inline Output Expression %%=Function()=%%

Used directly inside HTML markup or attributes to print the return value of a function—such as %%=v(@firstName)=%%, %%=ProperCase(@city)=%%, or %%=RedirectTo(@ctaUrl)=%%.

3. Functions vs. Statements vs. Strings 3 Construct Types

Functions use parentheses (Lookup(), IIF()); Language Statements control flow inside blocks (VAR, SET, IF/ENDIF, FOR/NEXT); Personalization Strings are system tokens (%%_subscriberkey%%).

Showing 32 of 32 entries

No matching AMPscript functions found

Try searching for another keyword such as LookupRows, AttributeValue, DateAdd, Substring, or RedirectTo.

1. String Functions

Concatenate, normalize casing, trim whitespace, search, slice, and replace text in SFMC

Concat()

#
String

Concatenates two or more strings, numbers, or variable values into a single returned string without requiring a separator character.

Verified SFMC Syntax Concat(string1, string2, [string3, ...])
AMPscript Example — Dynamic Full Name & UTM Link
%%[
VAR @firstName, @lastName, @fullName, @promoUrl
SET @firstName = ProperCase(AttributeValue("FirstName"))
SET @lastName = ProperCase(AttributeValue("LastName"))
SET @fullName = Concat(@firstName, " ", @lastName)
SET @promoUrl = Concat("https://www.ampscriptstudio.com/studio?utm_source=sfmc&sub=", AttributeValue("_subscriberkey"))
]%%
<p>Welcome back, %%=v(@fullName)=%%!</p>
<a href="%%=RedirectTo(@promoUrl)=%%">Launch Your Sandbox</a>
Expected Output Welcome back, Elena Rostova! (plus tracked anchor link)
Usage Notes & MCE Availability All MCE Channels. Unlike SQL or JavaScript, AMPscript does not use + to join strings. Always use Concat() and wrap dynamic href URLs in RedirectTo() inside Email sends.

ProperCase()

#
String

Capitalizes the first letter of each word in a string and converts all remaining letters in each word to lowercase.

Verified SFMC Syntax ProperCase(string)
AMPscript Example — Sanitizing Subscriber Names
%%[
VAR @rawName, @cleanName
SET @rawName = AttributeValue("FirstName") /* e.g. "mARCUS" or "SARAH JANE" */
IF NOT Empty(@rawName) THEN
  SET @cleanName = ProperCase(Trim(@rawName))
ELSE
  SET @cleanName = "Valued Trailblazer"
ENDIF
]%%
Hello %%=v(@cleanName)=%%,
Expected Output Hello Sarah Jane,
Usage Notes & MCE Availability All MCE Channels. Pair ProperCase() with Trim() to clean CRM imports where names are stored in all-caps or contain trailing spaces.

Uppercase() & Lowercase()

#
String

Uppercase() converts all characters in a string to capital letters; Lowercase() converts all characters to lowercase.

Verified SFMC Syntax Uppercase(string)  |  Lowercase(string)
AMPscript Example — Coupon Codes & Normalized Email Hashing
%%[
VAR @promoCode, @rawEmail, @normalizedEmail
SET @promoCode = Uppercase("sfmc25off")
SET @rawEmail = Trim(AttributeValue("EmailAddress"))
SET @normalizedEmail = Lowercase(@rawEmail)
]%%
Promo Code: <strong>%%=v(@promoCode)=%%</strong> (Sent to %%=v(@normalizedEmail)=%%)
Expected Output Promo Code: SFMC25OFF (Sent to alex@example.com)
Usage Notes & MCE Availability All MCE Channels. Always normalize email addresses with Lowercase(Trim(@email)) before passing them to SHA256() or MD5() for deterministic identity hashing.

Trim()

#
String

Removes leading and trailing whitespace characters from a string while preserving internal spaces between words.

Verified SFMC Syntax Trim(string)
AMPscript Example — Cleaning Whitespace-Padded Data Extension Fields
%%[
VAR @paddedCity, @cleanCity
SET @paddedCity = "   San Francisco   "
SET @cleanCity = Trim(@paddedCity)
]%%
City: "%%=v(@cleanCity)=%%" (Length: %%=Length(@cleanCity)=%%)
Expected Output City: "San Francisco" (Length: 13)
Usage Notes & MCE Availability All MCE Channels. If a Data Extension column contains only spaces (e.g. " "), Empty(@val) is false until you run Empty(Trim(@val)).

Length()

#
String

Returns the integer number of characters (including spaces and punctuation) in the specified string.

Verified SFMC Syntax Length(string)
AMPscript Example — Truncating Long Product Titles in Email Cards
%%[
VAR @productName, @displayTitle
SET @productName = "Salesforce Marketing Cloud Enterprise Architect Certification Bundle"
IF Length(@productName) > 36 THEN
  SET @displayTitle = Concat(Substring(@productName, 1, 33), "...")
ELSE
  SET @displayTitle = @productName
ENDIF
]%%
%%=v(@displayTitle)=%%
Expected Output Salesforce Marketing Cloud Enterp...
Usage Notes & MCE Availability All MCE Channels. Length("") returns 0. Do not confuse Length() (character count of a string) with RowCount() (number of rows in a Data Extension rowset).

Substring()

#
String

Extracts a portion of a string starting at a 1-based character position for a specified number of characters.

Verified SFMC Syntax Substring(string, startIndex, length)
AMPscript Example — Masking a Loyalty Card or Phone Number
%%[
VAR @cardNumber, @len, @lastFour, @maskedCard
SET @cardNumber = "4111222233338942"
SET @len = Length(@cardNumber)
SET @lastFour = Substring(@cardNumber, Subtract(@len, 3), 4)
SET @maskedCard = Concat("•••• •••• •••• ", @lastFour)
]%%
Card on file: %%=v(@maskedCard)=%%
Expected Output Card on file: •••• •••• •••• 8942
Usage Notes & MCE Availability All MCE Channels. startIndex is 1-based: the first character is at position 1. The third parameter is the character count to extract, not an ending index.

Replace() & ReplaceList()

#
String

Replace() substitutes all occurrences of a search substring with a replacement string. ReplaceList() replaces multiple delimited tokens in a single call.

Verified SFMC Syntax Replace(sourceString, searchString, replacementString)  |  ReplaceList(sourceString, replacementString, searchItem1, [searchItem2, ...])
AMPscript Example — Formatting Phone Numbers for tel: Links
%%[
VAR @rawPhone, @digitsOnly, @dashedPhone
SET @rawPhone = "(415) 555-0199"
SET @digitsOnly = ReplaceList(@rawPhone, "", "(", ")", " ", "-")
SET @dashedPhone = Replace(@rawPhone, " ", "-")
]%%
Dial: +1%%=v(@digitsOnly)=%% | Display: %%=v(@dashedPhone)=%%
Expected Output Dial: +14155550199 | Display: (415)-555-0199
Usage Notes & MCE Availability All MCE Channels. Note the parameter order difference: in Replace(source, search, replacement) the replacement string is 3rd, whereas in ReplaceList(source, replacement, search1, ...) the replacement string is 2nd.

IndexOf()

#
String

Returns the 1-based starting character position of the first occurrence of a substring within a string, or 0 if the substring is not found.

Verified SFMC Syntax IndexOf(sourceString, searchString)
AMPscript Example — Extracting the Domain Name from an Email Address
%%[
VAR @email, @atPos, @domainLen, @domain
SET @email = "architect@salesforce.com"
SET @atPos = IndexOf(@email, "@")
IF @atPos > 0 THEN
  SET @domainLen = Subtract(Length(@email), @atPos)
  SET @domain = Substring(@email, Add(@atPos, 1), @domainLen)
ENDIF
]%%
Email Domain: %%=v(@domain)=%%
Expected Output Email Domain: salesforce.com
Usage Notes & MCE Availability All MCE Channels. In AMPscript, IndexOf() returns 0 (not -1) when no match is found. Check IF IndexOf(@str, "token") > 0 THEN to test if a string contains a substring.

2. Date & Time Functions

Retrieve system timestamps, calculate expiration dates, measure intervals, and localize date formats

Now() & SystemDateToLocalDate()

#
Date & Time

Now() returns the current SFMC server system date and time (Central Standard Time, UTC-6 without daylight saving). SystemDateToLocalDate() converts server time to the authenticated SFMC user’s configured timezone.

Verified SFMC Syntax Now([preserveOriginalSendTimeBool])  |  SystemDateToLocalDate(dateTime)
AMPscript Example — Dynamic Copyright Year & Localized Timestamp
%%[
VAR @serverNow, @currentYear, @formattedToday
SET @serverNow = Now(1)
SET @currentYear = FormatDate(@serverNow, "yyyy")
SET @formattedToday = FormatDate(@serverNow, "MMMM dd, yyyy")
]%%
Generated on %%=v(@formattedToday)=%% · &copy; %%=v(@currentYear)=%%
Expected Output Generated on November 12, 2026 · © 2026
Usage Notes & MCE Availability All MCE Channels. In Email sends, passing Now(1) or Now(true) preserves the original job send timestamp when a subscriber clicks the View-As-Webpage (VAWP) link days later.

DateAdd()

#
Date & Time

Adds or subtracts a specified time interval (days, months, years, hours, minutes, or seconds) to a date and returns the resulting DateTime object.

Verified SFMC Syntax DateAdd(date, numericOffset, datePart)  /* datePart: "Y", "M", "D", "H", "MI", "S" */
AMPscript Example — 14-Day Coupon Expiration Deadline
%%[
VAR @today, @expiryDate, @expiryFormatted
SET @today = Now(1)
SET @expiryDate = DateAdd(@today, 14, "D")
SET @expiryFormatted = FormatDate(@expiryDate, "MMM dd, yyyy")
]%%
Offer expires in 14 days on <strong>%%=v(@expiryFormatted)=%%</strong>.
Expected Output Offer expires in 14 days on Nov 26, 2026.
Usage Notes & MCE Availability All MCE Channels. Pass a negative integer (e.g. DateAdd(Now(), -30, "D")) to look back in time. Note that minutes use "MI" whereas months use "M".

DateDiff()

#
Date & Time

Calculates the integer time difference between two dates (endDate - startDate) in the specified unit.

Verified SFMC Syntax DateDiff(startDate, endDate, datePart)  /* datePart: "Y", "M", "D", "H", "MI", "S" */
AMPscript Example — Calculating Trial Days Remaining
%%[
VAR @startDate, @renewalDate, @daysLeft
SET @startDate = DateParse("2026-11-12")
SET @renewalDate = AttributeValue("RenewalDate")
IF Empty(@renewalDate) THEN
  SET @renewalDate = DateParse("2026-11-19")
ENDIF
SET @daysLeft = DateDiff(@startDate, @renewalDate, "D")
]%%
You have %%=v(@daysLeft)=%% days remaining before your subscription renews.
Expected Output You have 7 days remaining before your subscription renews.
Usage Notes & MCE Availability All MCE Channels. DateDiff(@start, @end, "D") subtracts the first date from the second date. If @end is earlier than @start, the returned integer is negative.

FormatDate() & DateParse()

#
Date & Time

FormatDate() formats a DateTime value into a localized date/time string using pattern tokens. DateParse() converts a date string into a DateTime object.

Verified SFMC Syntax FormatDate(date, dateFormatPattern, [timeFormatPattern], [localeCode])  |  DateParse(dateString, [isUTCBoolean])
AMPscript Example — Locale-Aware Event Date Formatting
%%[
VAR @eventDate, @usFormat, @isoFormat
SET @eventDate = DateParse("2026-12-15 14:30:00", 0)
SET @usFormat = FormatDate(@eventDate, "MMMM dd, yyyy", "hh:mm tt", "en-US")
SET @isoFormat = FormatDate(@eventDate, "yyyy-MM-dd")
]%%
Webinar Date: %%=v(@usFormat)=%% (ISO: %%=v(@isoFormat)=%%)
Expected Output Webinar Date: December 15, 2026 02:30 PM (ISO: 2026-12-15)
Usage Notes & MCE Availability All MCE Channels. In FormatDate(), uppercase MM represents the month (01–12), whereas lowercase mm inside the 3rd parameter (timeFormatPattern) represents minutes. In DateParse(str, 1), passing 1 parses the input string as UTC.

3. Math & Logic Functions

Perform arithmetic calculations, modulo checks, inline ternary branches, and conditional control flow

Add(), Subtract(), Multiply(), Divide()

#
Math & Logic

Performs exact addition, subtraction, multiplication, and division on two numeric arguments. AMPscript uses explicit arithmetic functions instead of +, -, *, or / operators.

Verified SFMC Syntax Add(num1, num2)  |  Subtract(num1, num2)  |  Multiply(num1, num2)  |  Divide(num1, num2)
AMPscript Example — Calculating a 20% Promotional Discount
%%[
VAR @subtotal, @discountRate, @discountAmount, @finalTotal
SET @subtotal = 150
SET @discountRate = 0.20
SET @discountAmount = Multiply(@subtotal, @discountRate)
SET @finalTotal = Subtract(@subtotal, @discountAmount)
]%%
Original: %%=FormatCurrency(@subtotal, "en-US")=%% | You Pay: <strong>%%=FormatCurrency(@finalTotal, "en-US")=%%</strong>
Expected Output Original: $150.00 | You Pay: $120.00
Usage Notes & MCE Availability All MCE Channels. Never call Divide(@num, 0)—dividing by zero halts send or page execution. Guard denominators with IF @divisor != 0 THEN.

Mod() & Random()

#
Math & Logic

Mod() returns the remainder after dividing a dividend by a divisor. Random() generates a random integer inclusively between a lower and upper bound.

Verified SFMC Syntax Mod(dividend, divisor)  |  Random(lowerBound, upperBound)
AMPscript Example — Zebra-Striping Order Table Rows with Mod()
%%[
VAR @rowIndex, @rowBgColor, @luckyCode
SET @rowIndex = 2
SET @rowBgColor = IIF(Mod(@rowIndex, 2) == 0, "#f8fafc", "#ffffff")
SET @luckyCode = Random(1000, 9999)
]%%
Row Background: %%=v(@rowBgColor)=%% | Verification Pin: %%=v(@luckyCode)=%%
Expected Output Row Background: #f8fafc | Verification Pin: 4829
Usage Notes & MCE Availability All MCE Channels. Mod(@i, 2) == 0 is the standard SFMC idiom inside a FOR loop to alternate background colors on even vs. odd HTML table rows or split 2-column product grids.

IIF()

#
Math & Logic

Evaluates a boolean condition inline (ternary expression) and returns the second argument if true, or the third argument if false.

Verified SFMC Syntax IIF(booleanExpression, trueResult, falseResult)
AMPscript Example — One-Line Greeting & Pluralization
%%[
VAR @firstName, @orderCount
SET @firstName = AttributeValue("FirstName")
SET @orderCount = 1
]%%
Hi %%=IIF(NOT Empty(@firstName), ProperCase(@firstName), "Friend")=%%, you have %%=v(@orderCount)=%% %%=IIF(@orderCount == 1, "item", "items")=%% in your cart.
Expected Output Hi Friend, you have 1 item in your cart. (when FirstName is empty)
Usage Notes & MCE Availability All MCE Channels. IIF() evaluates both the true and false expressions before returning a result. Do not put functions with side effects (like InsertDE() or Divide() by a potentially zero variable) inside IIF(); use a full IF...THEN...ENDIF block instead.

VAR, SET, IF / ELSEIF / ENDIF, & FOR / NEXT Statements

#
Language Statements (Not Functions)

Core AMPscript language statements and keywords (distinct from callable functions) used inside %%[ ... ]%% blocks for variable declaration (VAR), assignment (SET), multi-branch conditional execution (IF / ELSEIF / ELSE / ENDIF), and bounded counter iteration (FOR @i = 1 TO @count DO ... NEXT @i).

Verified SFMC Language Statement Syntax VAR @var1, [@var2, ...]  |  SET @var = expression  |  IF condition THEN ... [ELSEIF condition THEN ...] [ELSE ...] ENDIF  |  FOR @var = startExpr TO|DOWNTO endExpr DO ... NEXT [@var]
AMPscript Example — Tiered Conditional Logic & FOR Loop Iteration
%%[
VAR @points, @tierName, @step, @milestoneList
SET @points = 3200
SET @milestoneList = ""

IF @points >= 5000 THEN
  SET @tierName = "Platinum"
ELSEIF @points >= 2500 AND @points < 5000 THEN
  SET @tierName = "Gold"
ELSE
  SET @tierName = "Member"
ENDIF

FOR @step = 1 TO 3 DO
  SET @milestoneList = Concat(@milestoneList, "Step ", @step, IIF(@step < 3, " -> ", ""))
NEXT @step
]%%
Current Tier: <strong>%%=v(@tierName)=%%</strong> (Path: %%=v(@milestoneList)=%%)
Expected Output Current Tier: Gold (Path: Step 1 -> Step 2 -> Step 3)
Usage Notes & MCE Availability All MCE Channels (Block Only). Because VAR, SET, IF, and FOR are language statements rather than functions, they can only be used inside %%[ ... ]%% blocks (never inside inline %%= ... =%% tags). Use ELSEIF as one word and close every IF with ENDIF and every FOR with NEXT @step.

4. Data Extension & Lookup Functions

Query relational SFMC Data Extensions, sort and iterate rowsets, and insert, upsert, or delete records

Lookup()

#
Data Extension

Queries a Data Extension and returns a single scalar column value from the first record matching one or more column/value filter pairs.

Verified SFMC Syntax Lookup(dataExtensionName, returnColumnName, matchColumnName1, matchValue1, [matchColumnName2, matchValue2, ...])
AMPscript Example — Fetching a Subscriber’s Loyalty Balance
%%[
VAR @subKey, @pointsBalance
SET @subKey = AttributeValue("_subscriberkey")
SET @pointsBalance = Lookup("Loyalty_Members", "PointsBalance", "SubscriberKey", @subKey)
IF Empty(@pointsBalance) THEN
  SET @pointsBalance = 0
ENDIF
]%%
Available Points: %%=FormatNumber(@pointsBalance, "N0", "en_US")=%%
Expected Output Available Points: 4,250
Usage Notes & MCE Availability All MCE Channels. Use Lookup() only when you need a single column from one row. If you need two or more fields from the same row, use LookupRows() instead so SFMC only queries the database once.

LookupRows() & LookupRowsCS()

#
Data Extension

Returns an unordered rowset (up to 2,000 rows) from a Data Extension matching one or more equality filter pairs. LookupRowsCS() performs a case-sensitive match.

Verified SFMC Syntax LookupRows(dataExtensionName, matchColumnName1, matchValue1, [matchColumnName2, matchValue2, ...])
AMPscript Example — Rendering Active Order Line Items
%%[
VAR @subKey, @orders, @count, @i, @row, @productName, @price
SET @subKey = AttributeValue("SubscriberKey")
SET @orders = LookupRows("Order_Items", "SubscriberKey", @subKey, "OrderStatus", "Shipped")
SET @count = RowCount(@orders)

IF @count > 0 THEN
  FOR @i = 1 TO @count DO
    SET @row = Row(@orders, @i)
    SET @productName = Field(@row, "ProductName")
    SET @price = Field(@row, "UnitPrice")
]%%
<li>%%=v(@productName)=%% — %%=FormatCurrency(@price, "en-US")=%%</li>
%%[
  NEXT @i
ENDIF
]%%
Expected Output <li>Cloud Architect Guide — $49.00</li>
Usage Notes & MCE Availability All MCE Channels. LookupRows() only supports exact equality (=) filters and caps output at 2,000 rows. Always verify RowCount(@rows) > 0 before calling Row(@rows, 1).

LookupOrderedRows() & LookupOrderedRowsCS()

#
Data Extension

Returns a sorted rowset limited to a specified maximum number of rows from a Data Extension using an SQL-style column ASC|DESC sort clause.

Verified SFMC Syntax LookupOrderedRows(dataExtensionName, numRowsToReturn, orderByClause, matchColumn1, matchValue1, ...)
AMPscript Example — Displaying the 3 Most Recent Purchases
%%[
VAR @subKey, @recentOrders, @rowCount, @i, @row, @orderId, @orderDate
SET @subKey = AttributeValue("SubscriberKey")
SET @recentOrders = LookupOrderedRows("Orders", 3, "OrderDate DESC", "SubscriberKey", @subKey)
SET @rowCount = RowCount(@recentOrders)

IF @rowCount > 0 THEN
  FOR @i = 1 TO @rowCount DO
    SET @row = Row(@recentOrders, @i)
    SET @orderId = Field(@row, "OrderID")
    SET @orderDate = FormatDate(Field(@row, "OrderDate"), "MMM dd, yyyy")
]%%
<p>Order #%%=v(@orderId)=%% placed on %%=v(@orderDate)=%%</p>
%%[
  NEXT @i
ENDIF
]%%
Expected Output Up to 3 most recent order records sorted newest-first by OrderDate DESC.
Usage Notes & MCE Availability All MCE Channels. Passing 0 or a number ≤ 0 for numRowsToReturn returns up to the default 2,000-row ceiling. Specify an explicit small limit (like 1, 3, or 5) to optimize send-time performance.

Row(), RowCount(), & DataExtensionRowCount()

#
Data Extension

RowCount() returns the integer number of rows in a lookup rowset. Row() extracts a single row object at a 1-based index. DataExtensionRowCount() returns the total record count of an entire Data Extension.

Verified SFMC Syntax RowCount(rowset)  |  Row(rowset, oneBasedRowIndex)  |  DataExtensionRowCount(dataExtensionName)
AMPscript Example — Safely Reading the First Matching Row
%%[
VAR @rows, @firstRow, @city, @state
SET @rows = LookupRows("Subscriber_Profiles", "SubscriberKey", AttributeValue("_subscriberkey"))
IF RowCount(@rows) > 0 THEN
  SET @firstRow = Row(@rows, 1)
  SET @city = Field(@firstRow, "City")
  SET @state = Field(@firstRow, "State")
ENDIF
]%%
Location: %%=v(@city)=%%, %%=v(@state)=%%
Expected Output Location: Austin, TX
Usage Notes & MCE Availability All MCE Channels. Calling Row(@rows, 1) on an empty rowset (where RowCount(@rows) == 0) or calling Row(@rows, 0) throws a fatal send-time exception.

Field()

#
Data Extension

Returns the value of a named column from a row object previously retrieved via Row().

Verified SFMC Syntax Field(rowObject, columnName, [throwErrorIfColumnMissingBool])
AMPscript Example — Null-Safe Column Extraction with Optional 3rd Parameter
%%[
VAR @rows, @row, @couponCode
SET @rows = LookupRows("Assigned_Coupons", "SubscriberKey", AttributeValue("_subscriberkey"))
IF RowCount(@rows) > 0 THEN
  SET @row = Row(@rows, 1)
  /* Pass 0 as 3rd argument to return "" instead of throwing an error if column is missing */
  SET @couponCode = Field(@row, "CouponCode", 0)
ENDIF
]%%
Your Coupon: %%=IIF(NOT Empty(@couponCode), @couponCode, "WELCOME10")=%%
Expected Output Your Coupon: VIP25 (or WELCOME10 if blank)
Usage Notes & MCE Availability All MCE Channels. By default, the 3rd parameter is true (throws an error if the column does not exist on the row). Passing 0 or false suppresses the exception and returns an empty string.

InsertDE(), UpdateDE(), UpsertDE(), DeleteDE() & *Data()

#
Data Extension (Channel-Restricted)

Modifies records in a Data Extension. The four *DE() functions (InsertDE, UpdateDE, UpsertDE, DeleteDE) are restricted to Email messages only (queued asynchronously at send time; return no output). The four *Data() functions (InsertData, UpdateData, UpsertData, DeleteData) execute synchronously and return the integer count of affected rows in CloudPages, landing pages, microsites, and SMS messages in MobileConnect.

Verified SFMC Syntax InsertDE(deName, col1, val1, ...)  |  InsertData(deName, col1, val1, ...)
UpdateDE(deName, numMatchCols, matchCol1, matchVal1, ..., writeCol1, writeVal1, ...)  |  UpdateData(deName, numMatchCols, matchCol1, matchVal1, ..., writeCol1, writeVal1, ...)
UpsertDE(deName, numMatchCols, matchCol1, matchVal1, ..., writeCol1, writeVal1, ...)  |  UpsertData(deName, numMatchCols, matchCol1, matchVal1, ..., writeCol1, writeVal1, ...)
DeleteDE(deName, matchCol1, matchVal1, ...)  |  DeleteData(deName, matchCol1, matchVal1, ...)
AMPscript Example — Channel A (Email Send Log) vs. Channel B (CloudPage / Landing Page / SMS Upsert)
%%[
VAR @subKey, @jobId, @rowsAffected
SET @subKey = AttributeValue("_subscriberkey")
SET @jobId = AttributeValue("jobid")

/* --- CHANNEL A: Email Messages ONLY (InsertDE, UpdateDE, UpsertDE, DeleteDE — async, no return value) --- */
UpsertDE("Email_Send_Audit_Log", 2, "SubscriberKey", @subKey, "JobID", @jobId, "SentAt", Now(1))

/* --- CHANNEL B: CloudPages, Landing Pages, Microsites & MobileConnect SMS (sync, returns row count) --- */
/* SET @rowsAffected = UpsertData("Subscriber_Preferences", 1, "SubscriberKey", @subKey, "OptIn", "True", "UpdatedAt", Now()) */
]%%
Logged send audit for Subscriber %%=v(@subKey)=%%.
Expected Output Logged send audit for Subscriber SUB-90421. (and queues the Email_Send_Audit_Log upsert at send time)
Usage Notes & MCE Channel Restrictions Per-Function MCE Channel Support:
• InsertDE(), UpdateDE(), UpsertDE(), DeleteDE(): Email messages only (asynchronous send-time batch execution; no output).
• InsertData(), UpdateData(), UpsertData(), DeleteData(): CloudPages, landing pages, microsites, and SMS messages in MobileConnect (synchronous execution; return integer affected row count).
Also note that UpdateDE / UpsertDE / UpdateData / UpsertData require numMatchCols as their 2nd parameter, whereas InsertDE / InsertData and DeleteDE / DeleteData do not take numMatchCols.

5. Utility & Formatting Functions

Safely read subscriber attributes, test for nulls, format numbers and currencies, and output variables

AttributeValue()

#
Utility

Safely retrieves the value of a subscriber attribute, sendable Data Extension column, or Journey Builder entry source field. Returns an empty string ("") instead of throwing a runtime error if the field does not exist.

Verified SFMC Syntax AttributeValue(attributeNameString)
AMPscript Example — Defensive Subscriber Attribute Retrieval
%%[
VAR @firstName, @loyaltyTier
SET @firstName = AttributeValue("FirstName")
SET @loyaltyTier = AttributeValue("LoyaltyTier")

IF Empty(@firstName) THEN
  SET @firstName = "Trailblazer"
ENDIF
IF Empty(@loyaltyTier) THEN
  SET @loyaltyTier = "Standard"
ENDIF
]%%
Welcome %%=ProperCase(@firstName)=%% (Tier: %%=v(@loyaltyTier)=%%)
Expected Output Welcome Trailblazer (Tier: Standard) (when attributes are missing or null)
Usage Notes & MCE Availability All MCE Channels. Always pass the attribute name inside quotes: AttributeValue("FirstName"). Never reference unquoted bare attributes in production templates that may be sent across multiple Data Extensions.

Empty() & IsNull()

#
Utility

Empty() returns true if a variable is NULL or an empty string (""). IsNull() returns true strictly when a variable holds a database NULL reference.

Verified SFMC Syntax Empty(expression)  |  IsNull(expression)
AMPscript Example — Checking Both Null and Blank Strings
%%[
VAR @company, @badgeText
SET @company = Trim(AttributeValue("CompanyName"))

IF NOT Empty(@company) THEN
  SET @badgeText = Concat("Team Workspace: ", @company)
ELSE
  SET @badgeText = "Individual Developer Account"
ENDIF
]%%
%%=v(@badgeText)=%%
Expected Output Individual Developer Account (when CompanyName is null, empty, or spaces)
Usage Notes & MCE Availability All MCE Channels. Because AttributeValue() coerces missing or null fields into "", IsNull(AttributeValue("Col")) evaluates to false! Always use Empty() instead of IsNull() for subscriber attributes.

v(), Output(), OutputLine(), & TreatAsContent()

#
Utility

v(@var) outputs the value of a variable inside inline %%=v(@var)=%% expressions. Output() and OutputLine() print values from inside a %%[ ... ]%% block. TreatAsContent() evaluates dynamic strings containing nested AMPscript or personalization tags.

Verified SFMC Syntax v(@variableName)  |  Output(expression)  |  OutputLine(expression)  |  TreatAsContent(stringWithAMPscript)
AMPscript Example — Block Output() vs. Inline %%=v()=%%
%%[
VAR @headline, @subhead
SET @headline = "Your SFMC Sandbox is Ready"
SET @subhead = "Zero enterprise license required."
Output(Concat("<h2>", @headline, "</h2>"))
]%%
<p>%%=v(@subhead)=%%</p>
Expected Output <h2>Your SFMC Sandbox is Ready</h2><p>Zero enterprise license required.</p>
Usage Notes & MCE Availability All MCE Channels. Output(@headline) alone does not print the variable value—you must pass a function call such as Output(v(@headline)) or Output(Concat(@headline)).

FormatCurrency(), FormatNumber(), Format(), & GUID()

#
Utility

Formats numeric or DateTime values into locale-specific currencies, numbers, or custom .NET format strings, and generates globally unique 36-character UUID v4 identifiers with GUID().

Verified SFMC Syntax FormatCurrency(number, localeCode, [decimalPlaces], [currencySymbol])  |  FormatNumber(number, formatType, [cultureCode])  |  Format(value, cSharpFormatPattern, [dateOrNumberType], [cultureCode])  |  GUID()
AMPscript Example — Multi-Currency Invoice, Number Formatting & GUID
%%[
VAR @amount, @usdPrice, @formattedQty, @paddedOrderNo, @requestId
SET @amount = 1499.5
SET @usdPrice = FormatCurrency(@amount, "en-US", 2)
SET @formattedQty = FormatNumber(12500, "N0", "en_US")
SET @paddedOrderNo = Format(42, "00000")
SET @requestId = GUID()
]%%
Total: %%=v(@usdPrice)=%% | Credits: %%=v(@formattedQty)=%% | Order #%%=v(@paddedOrderNo)=%% | Trace: %%=v(@requestId)=%%
Expected Output Total: $1,499.50 | Credits: 12,500 | Order #00042 | Trace: 8f14e45f-ceea-467f-a8c0-9d2c7120e1b4
Usage Notes & MCE Availability All MCE Channels. FormatNumber(number, formatType, [cultureCode]) takes 3 parameters where precision is embedded directly in formatType (standard numeric specifiers C, D, E, F, G, N, P, R, X with optional precision digits such as "N0", "N2", or "C2") and the 3rd parameter is an optional ISO/POSIX culture code ("en_US"). By contrast, Format(value, cSharpFormatPattern, [dateOrNumberType], [cultureCode]) accepts custom .NET pattern strings such as "00000", "#,##0.00", or date patterns.

6. HTTP, Content & CloudPages Functions

Track dynamic links, encrypt CloudPages parameters, read form submissions, and embed Content Builder blocks

RedirectTo(), Redirect(), & URLEncode()

#
HTTP & Links

RedirectTo() wraps a dynamic URL inside an HTML <a href="%%=RedirectTo(@url)=%%"> anchor attribute in HTML emails so Marketing Cloud Engagement wraps the link for click tracking and appends Web Analytics Connector (WAC) parameters. Separate from RedirectTo(), the Site function Redirect() performs an immediate server-side HTTP 302 browser redirect on a CloudPage, landing page, or microsite. URLEncode() percent-encodes URL strings.

Verified SFMC Syntax RedirectTo(urlString)  |  Redirect(redirectUrl)  |  URLEncode(urlString, [spaceAsPercent20Bool], [encodeAllCharsBool])
AMPscript Example — Tracked Personalized CTA Link in HTML Email
%%[
VAR @city, @encodedCity, @ctaUrl
SET @city = AttributeValue("City") /* e.g. "New York" */
SET @encodedCity = URLEncode(@city, 1, 1)
SET @ctaUrl = Concat("https://www.ampscriptstudio.com/events?city=", @encodedCity)
]%%
<a href="%%=RedirectTo(@ctaUrl)=%%" alias="Event_CTA">View Events in %%=v(@city)=%%</a>
Expected Output <a href="https://www.ampscriptstudio.com/events?city=New%20York" alias="Event_CTA">View Events in New York</a>
Usage Notes & MCE Channel Restrictions Do Not Conflate RedirectTo() and Redirect(): RedirectTo(urlString) is used inside the href attribute of an HTML <a> tag in HTML Email messages (and plain-text email URLs with http:// or https://) to enable SFMC click tracking; it does not perform a browser redirect. By contrast, Redirect(redirectUrl) is restricted to CloudPages, landing pages, and microsites only, where it immediately issues an HTTP 302 redirect response and terminates page execution.

CloudPagesURL()

#
CloudPages

Generates an encrypted URL to a published Marketing Cloud Engagement CloudPage using its numeric Page ID, automatically passing the subscriber context (_subscriberkey, emailaddr, jobid) plus any custom key-value parameters in a tamper-proof qs= token.

Verified SFMC Syntax CloudPagesURL(cloudPageId, [paramName1, paramValue1, paramName2, paramValue2, ...])
AMPscript Example — Secure 1-Click Preference Center Link
%%[
VAR @prefCenterUrl
/* Pass CloudPage ID 4821 and custom campaign parameters */
SET @prefCenterUrl = CloudPagesURL(4821, "source", "monthly_digest", "lang", "en")
]%%
<a href="%%=RedirectTo(@prefCenterUrl)=%%">Manage Email Preferences</a>
Expected Output Encrypted CloudPage URL containing ?qs=7f8a9b... (without exposing PII in plain text).
Usage Notes & MCE Channel Restrictions Email, SMS & CloudPages within the same MCE Enterprise. Always wrap CloudPagesURL() inside RedirectTo() when placing it in an HTML email <a href="..."> tag. On the destination CloudPage, read parameters via RequestParameter("source") or AttributeValue("_subscriberkey").

RequestParameter() & QueryParameter()

#
CloudPages Only

RequestParameter() retrieves a value from either an HTTP POST form submission, a URL query string parameter, or a decrypted CloudPagesURL() qs payload. QueryParameter() reads strictly from the URL query string or decrypted qs token.

Verified SFMC Syntax RequestParameter(parameterName)  |  QueryParameter(parameterName)
AMPscript Example — Processing a CloudPage Opt-In Form Submission
%%[
VAR @submitted, @email, @topic
SET @submitted = RequestParameter("submitted")
IF @submitted == "true" THEN
  SET @email = Lowercase(Trim(RequestParameter("email")))
  SET @topic = RequestParameter("topic")
  IF NOT Empty(@email) THEN
    UpsertData("Topic_Subscriptions", 1, "EmailAddress", @email, "Topic", @topic, "SubscribedAt", Now())
  ENDIF
ENDIF
]%%
Expected Output Reads submitted, email, and topic from the CloudPage HTTP request and upserts the record.
Usage Notes & MCE Channel Restrictions CloudPages, Microsites & Landing Pages Only. These functions require an active HTTP request context and are not applicable inside Email messages. Always sanitize inputs with Trim() and Empty() before passing them into UpsertData().

ContentBlockByKey(), ContentBlockById(), HTTPGet(), HTTPPost(), & RaiseError()

#
HTTP & Content

ContentBlockByKey() and ContentBlockById() render reusable Content Builder assets. HTTPGet() and HTTPPost() make external HTTP calls. RaiseError() halts an email send for either the current subscriber or the entire send job when mandatory data is missing.

Verified SFMC Syntax ContentBlockByKey(customerKey, [impressionRegion], [continueOnErrorBool], [defaultContent], [@statusOut])  |  ContentBlockById(assetId, ...)
HTTPGet(url, [continueOnErrorBool], [emptyContentModeInt], [@statusOut])  |  HTTPPost(url, contentType, payloadString, [@responseOut], [headerName1, headerVal1, ...])
RaiseError(errorMessage, [skipCurrentSubscriberOnlyBool], [apiErrorCode], [apiErrorNumber], [preserveDataExtensionWritesBool])
AMPscript Example — Modular Header Block & Send-Time Guardrail
%%[
VAR @subKey, @price
SET @subKey = AttributeValue("_subscriberkey")
SET @price = Lookup("Order_Summary", "TotalAmount", "SubscriberKey", @subKey)

/* Skip ONLY this subscriber (2nd arg = true) and preserve prior DE writes (5th arg = true) */
IF Empty(@price) THEN
  UpsertDE("Send_Error_Log", 1, "SubscriberKey", @subKey, "Reason", "Missing TotalAmount")
  RaiseError("Missing mandatory TotalAmount for subscriber", true, "MISSING_TOTAL", 1001, true)
ENDIF
]%%
%%=ContentBlockByKey("Global_Brand_Header_2026")=%%
Expected Output Renders the Global_Brand_Header_2026 Content Builder block, or logs the error and cleanly skips only the affected subscriber if @price is empty.
Usage Notes & MCE Channel Restrictions In RaiseError(msg, true, code, num, true), always set the 2nd parameter to true (1) to skip only the current subscriber (passing false aborts the entire email job!) and set the 5th parameter to true if you want prior InsertDE/UpsertDE error logs to be committed instead of rolled back. Avoid HTTPGet/HTTPPost in high-volume bulk email sends due to external latency.

7. Email Personalization Strings (System Tokens)

Built-in Marketing Cloud Engagement system replacement tokens (distinct from callable functions) for subscriber identity, send context, and CAN-SPAM compliance

Subscriber & Send Context Personalization Strings

#
System Personalization Strings (Not Functions)

Built-in Marketing Cloud Engagement system personalization strings (not callable functions) that expose the active subscriber’s primary key, email address, MID (Business Unit ID), Job ID, and current rendering context (SEND, PREVIEW, VAWP, or FTAF).

Verified SFMC Personalization String Tokens %%_subscriberkey%%  |  %%emailaddr%%  |  %%jobid%%  |  %%memberid%%  |  %%_messagecontext%%
AMPscript Example — Assigning System Strings Inside a Code Block
%%[
VAR @subKey, @email, @jobId, @mid, @context
/* Inside %%[ ]%% blocks, reference system strings via AttributeValue() or bare token names (no %% delimiters) */
SET @subKey = AttributeValue("_subscriberkey")
SET @email = AttributeValue("emailaddr")
SET @jobId = jobid
SET @mid = memberid
SET @context = _messagecontext
]%%
Subscriber: %%=v(@subKey)=%% (MID: %%=v(@mid)=%% | Job: %%=v(@jobId)=%% | Context: %%=v(@context)=%%)
Expected Output Subscriber: SUB-90421 (MID: 514009821 | Job: 184290 | Context: SEND)
Usage Notes & MCE Channel Restrictions Email, SMS & CloudPages (via CloudPagesURL). Personalization strings do not use parentheses. Inside HTML markup, wrap them in double percent signs (%%_subscriberkey%%); inside a %%[ ... ]%% block, omit the %% delimiters or pass the token name into AttributeValue("_subscriberkey").

View-As-Webpage & CAN-SPAM Compliance Strings

#
System Personalization Strings (Email Only)

System-generated URLs and physical sender address personalization strings required by Marketing Cloud Engagement’s commercial email validation engine and CAN-SPAM compliance checks.

Verified SFMC Personalization String Tokens %%view_email_url%%  |  %%profile_center_url%%  |  %%subscription_center_url%%  |  %%unsub_center_url%%  |  %%Member_Busname%%  |  %%Member_Addr%%, %%Member_City%%, %%Member_State%% %%Member_PostalCode%%, %%Member_Country%%
AMPscript Example — Compliant Commercial Email Footer & VAWP Banner
%%[ IF _messagecontext != "VAWP" THEN ]%%
  <p><a href="%%view_email_url%%">View this email in your browser</a></p>
%%[ ENDIF ]%%

<footer>
  <p>Sent by %%Member_Busname%% · %%Member_Addr%%, %%Member_City%%, %%Member_State%% %%Member_PostalCode%%, %%Member_Country%%</p>
  <p>
    <a href="%%profile_center_url%%">Update Profile</a> |
    <a href="%%unsub_center_url%%">One-Click Unsubscribe</a>
  </p>
</footer>
Expected Output Hides the “View in browser” banner when the subscriber is already viewing the web version (_messagecontext == "VAWP") and renders the physical sender address and unsubscribe links.
Usage Notes & MCE Channel Restrictions Email Messages Only. Commercial Send Classifications in Marketing Cloud Engagement fail pre-send validation unless the email template contains %%profile_center_url%% (or %%unsub_center_url%%) and the Business Unit’s physical mailing address tokens (%%Member_Busname%%, %%Member_Addr%%, etc.).

Common AMPscript Mistakes & Defensive SFMC Patterns

Avoid the 4 most frequent send-time errors encountered in Salesforce Marketing Cloud production journeys

1. Bare Personalization Strings vs. AttributeValue()

Avoid (Fails if column is missing from DE): Hello %%FirstName%%!
Best Practice (Null-safe across all Sendable DEs): %%[ SET @fn = AttributeValue("FirstName") ]%% Hello %%=IIF(NOT Empty(@fn), ProperCase(@fn), "there")=%%!

2. Calling Row(@rs, 1) Without Checking RowCount()

Avoid (Throws out-of-bounds error when 0 rows match): SET @rows = LookupRows("Orders", "SubKey", @subKey) SET @row = Row(@rows, 1)
Best Practice (Always guard with RowCount() > 0): SET @rows = LookupRows("Orders", "SubKey", @subKey) IF RowCount(@rows) > 0 THEN SET @row = Row(@rows, 1) ENDIF

3. Mixing Up InsertDE() and InsertData()

Avoid (Using InsertData inside an Email): /* Inside an Email template - FAILS */ SET @n = InsertData("SendLog", "SubKey", @subKey)
Best Practice (Match function suffix to channel): /* Emails ONLY: InsertDE / UpdateDE / UpsertDE / DeleteDE */ InsertDE("SendLog", "SubKey", @subKey) /* CloudPages, Landing Pages, Microsites & MobileConnect SMS: InsertData / UpdateData / UpsertData / DeleteData */

4. Unwrapped Dynamic URLs in HTML Anchor Tags

Avoid (Breaks SFMC Click Tracking & WAC): <a href="%%=v(@dynamicUrl)=%%">Shop Now</a>
Best Practice (Always wrap dynamic hrefs in RedirectTo): <a href="%%=RedirectTo(@dynamicUrl)=%%">Shop Now</a>

Frequently Asked Questions About AMPscript Functions

Answers to common technical questions from Salesforce Marketing Cloud developers
1. What is the difference between Lookup() and LookupRows() in AMPscript?
Lookup() returns a single scalar column value from a Data Extension when you only need one field (such as a LoyaltyTier or FirstName). LookupRows() returns a multi-row rowset (up to 2,000 rows) that you inspect with RowCount(), extract individual records from using Row(@rowset, @index), and read multiple columns from using Field(@row, "ColumnName"). When you need two or more columns from the same Data Extension record, calling LookupRows() once is more efficient than calling Lookup() multiple times.
2. Why should I use AttributeValue() instead of bare personalization strings like %%FirstName%%?
Referencing a bare personalization string like %%FirstName%% when that column does not exist in the sendable Data Extension throws a hard send-time error and aborts the email render for that subscriber. AttributeValue("FirstName") safely returns an empty string ("") if the attribute is missing or null, allowing you to pair it with Empty(@firstName) to provide a clean fallback greeting.
3. Are AMPscript string and rowset functions 0-indexed or 1-indexed?
All AMPscript positional functions are strictly 1-indexed. In Substring(@str, 1, 4), character position 1 is the first character. In IndexOf(@str, "@"), position 1 is the first character and 0 means the substring was not found. In Row(@rowset, 1), row index 1 is the first record returned by LookupRows() or LookupOrderedRows(). Calling Row(@rowset, 0) throws a runtime out-of-bounds error.
4. What is the difference between InsertDE() and InsertData() in Salesforce Marketing Cloud?
InsertDE(), UpdateDE(), UpsertDE(), and DeleteDE() are reserved exclusively for Email messages; they queue Data Extension modifications asynchronously at send time and do not return a row count. InsertData(), UpdateData(), UpsertData(), and DeleteData() execute synchronously on CloudPages, landing pages, microsites, and SMS messages in MobileConnect, and return the integer number of affected rows.
5. What is the difference between Empty() and IsNull() in AMPscript?
IsNull(@var) only returns true when a variable holds a database NULL reference, and returns false for an empty string (""). Because AttributeValue() converts missing or null subscriber attributes into empty strings, IsNull() will evaluate to false on empty AttributeValue() results. Empty(@var) checks for both NULL and empty string ("") values, making Empty() the recommended function for defensive validation in SFMC.
6. When do I need to wrap a dynamic URL in RedirectTo()?
In Salesforce Marketing Cloud HTML emails, whenever the href attribute of an anchor tag (<a href="...">) is populated dynamically using an AMPscript variable or Concat() expression, you must wrap it in %%=RedirectTo(@url)=%% so SFMC's click-tracking wrapper (WAC / Link Wrapping) can register and track the link properly.
7. Are AMPscript function names and variable names case-sensitive?
No. AMPscript is case-insensitive for function names (LookupRows, LOOKUPROWS, and lookuprows behave identically), variable identifiers (@firstName and @FIRSTNAME refer to the same variable), and string comparisons using == unless you explicitly use case-sensitive functions like LookupRowsCS() or LookupOrderedRowsCS().
8. Can I test these AMPscript functions online without a Salesforce Marketing Cloud license?
Yes. You can copy any code snippet on this reference page and run it immediately in the free AMPscript Studio sandbox at ampscriptstudio.com/studio, or practice structured hands-on coding exercises in AMPscript Academy at ampscriptstudio.com/academy without needing an enterprise Salesforce Marketing Cloud org.

Test Any AMPscript Function Live in Your Browser

Paste any snippet from this reference into the AMPscript Studio sandbox to test it against relational mock Data Extensions, or build hands-on mastery in AMPscript Academy.