AMPscript Cheat Sheet

Short, correct AMPscript snippets for the things you write every week: variables, fallbacks, lookups, loops over rows, dates, strings and tracked links.

Type
Resource
Topic
Resource
Reading time
4 min
Updated
Author
GeekMidst Team
Reviewed by
Site owner
Talk to an expert
Cover of the GeekMidst AMPscript Cheat Sheet (cheat sheet), listing sections: Syntax basics, Conditionals, Lookups and loops

This is a working reference for AMPscript in Marketing Cloud Engagement emails, SMS and CloudPages. The snippets are short on purpose. They use sample data extension names such as Orders_DE and Loyalty_DE; swap in your own names and fields, and test every change with real and edge-case data before it goes near a live send.

Syntax basics

  • Code blocks sit inside %%[ ... ]%%. Inline output uses %%=v(@variable)=%% or %%=FunctionName(...)=%%.
  • Declare variables with VAR, assign with SET. Variable names start with @.
  • String literals use double or single quotes. Function names and keywords are not case sensitive, but keep a consistent style.
  • Comments use /* ... */ inside a code block.
  • _subscriberkey and emailaddr are system personalisation strings available in send context.
ampscript
%%[
/* Greeting with a fallback */
VAR @firstName, @greeting
SET @firstName = AttributeValue("FirstName")

IF Empty(@firstName) THEN
  SET @firstName = "there"
ENDIF

SET @greeting = Concat("Hi ", ProperCase(@firstName))
]%%
<p>%%=v(@greeting)=%%,</p>
Variables, a fallback and inline output

AttributeValue() returns an empty value rather than failing when the attribute is missing from the sending context, which makes it safer than referencing [FirstName] directly in shared content blocks.

Conditionals

Use IF ... ELSEIF ... ELSE ... ENDIF for anything with more than one outcome. For a simple inline choice, IIF(condition, valueIfTrue, valueIfFalse) keeps the HTML readable. Comparison operators are ==, !=, >, <, >=, <=, combined with AND, OR and NOT.

Lookups and loops

Lookup() returns one field from the first matching row. LookupRows() returns a rowset of matching rows, and LookupOrderedRows() lets you set how many rows to return and the sort order. Always check RowCount() before looping.

ampscript
%%[
VAR @tier, @rows, @rowCount, @i, @row, @orderId, @total

SET @tier = Lookup("Loyalty_DE", "Tier", "SubscriberKey", _subscriberkey)

/* Three most recent orders, newest first */
SET @rows = LookupOrderedRows("Orders_DE", 3, "OrderDate DESC", "SubscriberKey", _subscriberkey)
SET @rowCount = RowCount(@rows)

IF @rowCount > 0 THEN
  FOR @i = 1 TO @rowCount DO
    SET @row = Row(@rows, @i)
    SET @orderId = Field(@row, "OrderID")
    SET @total = Field(@row, "OrderTotal")
]%%
<p>Order %%=v(@orderId)=%%: %%=FormatCurrency(@total, "en-GB")=%%</p>
%%[
  NEXT @i
ELSE
]%%
<p>You have no recent orders.</p>
%%[
ENDIF
]%%
Single-value lookup and a loop over ordered rows

Functions you will use most

FunctionWhat it doesExample
Empty(value)True if the value is null or an empty stringIF Empty(@city) THEN
IIF(test, a, b)Inline ifIIF(@tier == "Gold", "Gold member", "Member")
Concat(a, b, ...)Joins stringsConcat(@first, " ", @last)
ProperCase, Uppercase, LowercaseChange caseProperCase(@firstName)
Trim(value)Removes leading and trailing spacesTrim(@postcode)
Substring(s, start, length)Part of a string, starting at position 1Substring(@code, 1, 3)
IndexOf(s, search)Position of a substring, counting from 1IndexOf(@email, "@")
Replace(s, find, with)Replaces textReplace(@phone, " ", "")
FormatNumber(n, format)Formats numbersFormatNumber(@points, "N0")

Dates

Now() returns the current system date and time. Marketing Cloud system time is Central Standard Time without daylight saving adjustment, so convert with SystemDateToLocalDate() when you need local time. It uses the time zone set in the account or user settings, not the subscriber's own time zone, so check how it behaves in your account. Use DateAdd() and DateDiff() for arithmetic and FormatDate() for display.

ampscript
%%[
VAR @expiry, @daysLeft
SET @expiry = DateAdd(Now(), 14, "D")
SET @daysLeft = DateDiff(Now(), @expiry, "D")
]%%
<p>Your offer ends on %%=FormatDate(@expiry, "dd MMMM yyyy")=%% (%%=v(@daysLeft)=%% days).</p>
Adding days and formatting a date
  • For a link built from variables, wrap the URL in RedirectTo() inside the href so click tracking still works: <a href="%%=RedirectTo(@productUrl)=%%">View product</a>.
  • CloudPagesURL(pageId, "key", value) builds an encrypted link to a CloudPage and passes subscriber context, which is safer than putting email addresses in query strings.
  • On a CloudPage, RequestParameter("key") reads a posted or query string value. Validate and sanitise anything that arrives this way.

Stopping a send for one subscriber

RaiseError("Missing order data", true) skips the current subscriber instead of sending a broken email. Use it when required data is missing, and monitor how often it fires: a sudden increase usually means an upstream data feed has failed.

Common mistakes

  1. Looping without checking RowCount() first, which breaks when there are no rows.
  2. Assuming Lookup() returns the newest row. It returns the first match; use LookupOrderedRows() when order matters.
  3. Comparing numbers stored as text. Check the data extension field type before using > or <.
  4. Personalising subject lines with fields that are often empty, with no fallback.
  5. Testing only with a perfect test record. Always preview with a subscriber whose data is incomplete.

For deeper guidance see LookupRows vs LookupOrderedRows, how to debug AMPscript personalisation errors, AMPscript vs Server-Side JavaScript and our AMPscript development service. The full function reference lives in the Salesforce developer documentation.

Need AMPscript you can trust?

We write, review and debug AMPscript for emails, SMS and CloudPages, with test cases for the edge cases.

Talk to an AMPscript developer →

Tell us what you are trying to fix.

Share your Salesforce setup, goals and constraints. A practitioner reads every message and replies with questions, first thoughts or an honest view of whether you need outside help at all.

Talk to a Salesforce Expert
Book a Consultation