SQL is the most useful skill you can learn in Marketing Cloud Engagement. Almost every audience, report and clean-up job ends up as a SQL Query activity somewhere. This guide starts with the basics and builds up to the patterns you will use every week: dates, joins, data views, totals, CASE and removing duplicates.
How a query activity works
A SQL Query activity in Automation Studio runs a SELECT statement and writes the result into a target data extension. It doesn't change the source data. You can't run UPDATE, DELETE or INSERT statements. Every query reads data and writes the result somewhere.
When you create the activity, you pick a data action for the target:
| Data action | What happens |
|---|---|
| Overwrite | The target is emptied, then filled with the new results |
| Update | Rows are matched on the target's primary key. Matches are updated and new rows are added |
| Append | New rows are added. Existing rows stay as they are |
Use Update when the target has a primary key and you want to keep history. Use Overwrite for audiences you rebuild from scratch each run.
💡 Column names must match
The names in your SELECT must match the target data extension's field names. If a name doesn't match, or a value is longer than the target field allows, the query fails. Use AS to rename columns so they line up.
Basic SELECT
Name the columns you need. Avoid SELECT *. It is slower and breaks easily when someone adds a field to the source.
SELECT
SubscriberKey,
EmailAddress,
FirstName,
LastName
FROM Customers
WHERE Status = 'Active'
AND EmailOptIn = 1 If a data extension name has spaces or special characters, wrap it in square brackets: FROM [Customer Master].
Marketing Cloud SQL follows SQL Server syntax. To test a query on a small sample, use TOP, not LIMIT:
SELECT TOP 100
SubscriberKey,
EmailAddress
FROM Customers Working with dates
Date filters are behind most audiences: "signed up this week", "bought in the last 90 days", "birthday next month".
SELECT
SubscriberKey,
EmailAddress,
SignupDate,
DATEDIFF(DAY, SignupDate, GETDATE()) AS DaysSinceSignup
FROM Customers
WHERE SignupDate >= DATEADD(DAY, -7, GETDATE()) A few functions you will use all the time:
GETDATE()returns the current date and timeDATEADD(DAY, -30, GETDATE())gives the date 30 days ago. You can useMONTH,YEARorHOURinstead ofDAYDATEDIFF(DAY, StartDate, EndDate)counts the days between two datesCONVERT(DATE, SomeDateTime)drops the time part, which helps when you compare whole days
⚠️ Server time is not your local time
GETDATE() returns the Marketing Cloud server time, not your business time zone. If a filter must line up with midnight in your own time zone, test it with a few known records before you trust it.
Joining data extensions
Joins let you combine data from more than one data extension. Always give each table a short alias and prefix every column with it. It makes the query easier to read and avoids "ambiguous column" errors.
SELECT
c.SubscriberKey,
c.EmailAddress,
c.FirstName,
l.Tier,
l.PointsBalance
FROM Customers c
INNER JOIN Loyalty_Members l
ON l.SubscriberKey = c.SubscriberKey
WHERE c.Status = 'Active' An INNER JOIN keeps only customers who have a loyalty record. To find people who don't have a match, use a LEFT JOIN and check for NULL:
SELECT
c.SubscriberKey,
c.EmailAddress
FROM Customers c
LEFT JOIN Loyalty_Members l
ON l.SubscriberKey = c.SubscriberKey
WHERE l.SubscriberKey IS NULL This "left join and check for null" pattern is one of the most useful in Marketing Cloud. You will use it for exclusions all the time.
Using data views
Data views are system tables that hold sending and engagement data, such as _Sent, _Open, _Click, _Bounce, _Unsubscribe and _Job. You can query them like data extensions.
SELECT DISTINCT
o.SubscriberKey
FROM _Open o
WHERE o.EventDate >= DATEADD(DAY, -30, GETDATE())
AND o.IsUnique = 1 Keep two things in mind:
- Most engagement data views only hold about the last six months. Salesforce also recommends keeping data view queries to a six-month range or less.
- Data views can be very large. Filter by date first, and pull only the columns you need.
Totals with GROUP BY
Aggregate functions like COUNT, SUM, AVG, MIN and MAX work with GROUP BY. Every column in the SELECT that isn't aggregated must be in the GROUP BY.
SELECT
o.SubscriberKey,
COUNT(o.OrderId) AS OrderCount,
SUM(o.OrderTotal) AS TotalSpend,
MAX(o.OrderDate) AS LastOrderDate
FROM Orders o
WHERE o.OrderDate >= DATEADD(MONTH, -12, GETDATE())
GROUP BY o.SubscriberKey
HAVING COUNT(o.OrderId) >= 2 WHERE filters rows before they are grouped. HAVING filters the groups after. Here, HAVING keeps only customers with at least two orders.
Labels with CASE
CASE lets you create a value based on conditions. It checks each WHEN from top to bottom and uses the first one that is true. Always add an ELSE, or you get NULL when nothing matches.
SELECT
t.SubscriberKey,
t.TotalSpend,
CASE
WHEN t.TotalSpend >= 1000 THEN 'Gold'
WHEN t.TotalSpend >= 250 THEN 'Silver'
ELSE 'Bronze'
END AS SpendTier
FROM Customer_Totals t Storing the tier in a data extension means your email can show %%SpendTier%% directly, without extra AMPscript.
Removing duplicates
Source data often has the same person more than once. ROW_NUMBER() lets you number the rows for each person and keep only the first one.
SELECT
x.SubscriberKey,
x.EmailAddress,
x.FirstName
FROM (
SELECT
c.SubscriberKey,
c.EmailAddress,
c.FirstName,
ROW_NUMBER() OVER (
PARTITION BY c.EmailAddress
ORDER BY c.ModifiedDate DESC
) AS rn
FROM Customers c
) x
WHERE x.rn = 1 PARTITION BY decides what counts as a duplicate, here the email address. ORDER BY decides which row wins, here the most recently changed one.
Keep queries fast
Query activities time out after 30 minutes. These habits, taken from Salesforce's own guidance, keep you well under that:
- Select only the columns you need, and include the target's primary key
- Size text fields to what they really hold instead of the default 50 characters
- Store numbers as Number fields, not Text
- Limit data view queries to a short date range
- Split one huge query into smaller steps that each write to their own data extension, then join the results
- Give each query its own step in the automation
Quick reference
| Task | Pattern |
|---|---|
| Sample rows | SELECT TOP 100 ... |
| Last N days | WHERE DateField >= DATEADD(DAY, -N, GETDATE()) |
| Find non-matches | LEFT JOIN ... WHERE right.Key IS NULL |
| Totals per person | GROUP BY SubscriberKey with SUM or COUNT |
| Filter on totals | HAVING COUNT(...) >= 2 |
| Labels | CASE WHEN ... THEN ... ELSE ... END |
| One row per person | ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) |