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. Strings3 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
%%[
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 OutputWelcome back, Elena Rostova! (plus tracked anchor link)
Usage Notes & MCE AvailabilityAll 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.
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 OutputHello Sarah Jane,
Usage Notes & MCE AvailabilityAll MCE Channels. Pair ProperCase() with Trim() to clean CRM imports where names are stored in all-caps or contain trailing spaces.
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 OutputPromo Code: SFMC25OFF (Sent to alex@example.com)
Usage Notes & MCE AvailabilityAll MCE Channels. Always normalize email addresses with Lowercase(Trim(@email)) before passing them to SHA256() or MD5() for deterministic identity hashing.
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 OutputCity: "San Francisco" (Length: 13)
Usage Notes & MCE AvailabilityAll MCE Channels. If a Data Extension column contains only spaces (e.g. " "), Empty(@val) is false until you run Empty(Trim(@val)).
Usage Notes & MCE AvailabilityAll MCE Channels.Length("") returns 0. Do not confuse Length() (character count of a string) with RowCount() (number of rows in a Data Extension rowset).
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 OutputCard on file: •••• •••• •••• 8942
Usage Notes & MCE AvailabilityAll 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() substitutes all occurrences of a search substring with a replacement string. ReplaceList() replaces multiple delimited tokens in a single call.
Usage Notes & MCE AvailabilityAll 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.
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 OutputEmail Domain: salesforce.com
Usage Notes & MCE AvailabilityAll 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() 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.
Usage Notes & MCE AvailabilityAll 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.
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 OutputOffer expires in 14 days on Nov 26, 2026.
Usage Notes & MCE AvailabilityAll 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".
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 OutputYou have 7 days remaining before your subscription renews.
Usage Notes & MCE AvailabilityAll 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() formats a DateTime value into a localized date/time string using pattern tokens. DateParse() converts a date string into a DateTime object.
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 OutputWebinar Date: December 15, 2026 02:30 PM (ISO: 2026-12-15)
Usage Notes & MCE AvailabilityAll 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
Performs exact addition, subtraction, multiplication, and division on two numeric arguments. AMPscript uses explicit arithmetic functions instead of +, -, *, or / operators.
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 OutputOriginal: $150.00 | You Pay: $120.00
Usage Notes & MCE AvailabilityAll MCE Channels. Never call Divide(@num, 0)—dividing by zero halts send or page execution. Guard denominators with IF @divisor != 0 THEN.
Usage Notes & MCE AvailabilityAll 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.
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 OutputHi Friend, you have 1 item in your cart. (when FirstName is empty)
Usage Notes & MCE AvailabilityAll 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
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)=%%)
Usage Notes & MCE AvailabilityAll 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
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 OutputAvailable Points: 4,250
Usage Notes & MCE AvailabilityAll 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.
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.
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
]%%
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 AvailabilityAll 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.
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.
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 OutputYour Coupon: VIP25 (or WELCOME10 if blank)
Usage Notes & MCE AvailabilityAll 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.
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.
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.
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 OutputWelcome Trailblazer (Tier: Standard) (when attributes are missing or null)
Usage Notes & MCE AvailabilityAll 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.
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 OutputIndividual Developer Account (when CompanyName is null, empty, or spaces)
Usage Notes & MCE AvailabilityAll 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(@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.
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 AvailabilityAll 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)).
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().
Usage Notes & MCE AvailabilityAll 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() 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.
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 RestrictionsDo 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.
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.
Usage Notes & MCE Channel RestrictionsEmail, 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() 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.
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 RestrictionsCloudPages, 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() 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.
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
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).
Usage Notes & MCE Channel RestrictionsEmail, 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").
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 RestrictionsEmail 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 */
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.