Home
/
Blog
/
Engineering
Engineering

ROW_NUMBER in SFMC SQL: Latest Record per Subscriber (Examples)

Use ROW_NUMBER() in SFMC SQL to keep the latest record per subscriber, dedupe a data extension and rank top-N rows, with copy-ready query activity examples.

You have a data extension with several rows per subscriber (orders, form submissions, imports that were never cleaned) and the campaign only wants one of them: the newest, the biggest, or the one with the right status. A plain WHERE cannot express "the latest row for each person", and GROUP BY loses the other columns on that row.

The answer is ROW_NUMBER() OVER (PARTITION BY SubscriberKey ORDER BY ... DESC) in a subquery, then WHERE rn = 1 outside it. That is the whole trick behind ROW_NUMBER in SFMC SQL, and it runs fine in an Automation Studio query activity.

‍

This guide covers how ROW_NUMBER() works in Marketing Cloud, why the subquery is mandatory, how to keep the result stable, when RANK() fits better, and how CASE WHEN turns a latest record into a segment.

‍

ROW_NUMBER in SFMC SQL: what it does

‍

ROW_NUMBER() is a window function. It looks at a set of rows, splits them into groups you define, sorts each group, and writes a counter next to each row: 1, 2, 3 and so on. Nothing is aggregated, every input row survives, it just gains a number.

Marketing Cloud's query activity accepts the SQL Server dialect. Salesforce's own SQL reference describes support as based on, but not identical to, SQL Server 2016, and window functions are part of what works. What does not work is just as important: no variables, no temporary tables, no common table expressions (WITH), no cursors. If you want to generate SFMC SQL from a plain-English request, this is exactly the kind of pattern a generator should know by heart, because hand-writing it is where most mistakes happen.

‍

The anatomy of ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)

Three parts matter. PARTITION BY decides where the counter restarts, almost always SubscriberKey in SFMC. ORDER BY decides which row gets number 1 inside each partition, and its direction (DESC for newest first) encodes your business rule. The alias after AS is how you refer to the number later.

ROW_NUMBER() requires an ORDER BY inside OVER(); leave it out and the query is refused. PARTITION BY is optional, but without it you get one running count across the whole table.

‍

Why the subquery is mandatory in a query activity

You cannot write WHERE ROW_NUMBER() OVER (...) = 1. SQL Server evaluates WHERE before window functions and answers that windowed functions can only appear in the SELECT or ORDER BY clauses. The fix is always the same: compute the number in an inner SELECT, wrap it as a derived table, and filter on the alias outside.

Since WITH is not available in Marketing Cloud, a derived table in FROM (...) AS alias is the only way to layer the logic.

‍

Latest record per subscriber: the core example

‍

The most common request is the most recent purchase or form submission for every subscriber, with all its columns. A complete query you can paste into a query activity:

SELECT
    SubscriberKey,
    EmailAddress,
    OrderID,
    OrderDate,
    OrderTotal
FROM (
    SELECT
        o.SubscriberKey,
        o.EmailAddress,
        o.OrderID,
        o.OrderDate,
        o.OrderTotal,
        ROW_NUMBER() OVER (
            PARTITION BY o.SubscriberKey
            ORDER BY o.OrderDate DESC, o.OrderID DESC
        ) AS rn
    FROM Orders_History o
    WHERE o.OrderDate >= DATEADD(MONTH, -12, GETDATE())
) AS ranked
WHERE rn = 1
  • The inner SELECT reads Orders_History and keeps the five columns the campaign needs.
  • The WHERE on OrderDate limits the input to the last 12 months, so the window only numbers rows that can win.
  • ROW_NUMBER() restarts at 1 for every SubscriberKey, ordered by OrderDate newest first, with OrderID as a tiebreaker.
  • The derived table is aliased as ranked; every derived table needs an alias.
  • The outer WHERE rn = 1 keeps exactly one row per subscriber, and rn itself is not selected so it never lands in the target.

Target data extension: Latest_Order_Per_Subscriber, primary key SubscriberKey, data action Overwrite. The query guarantees one row per key, so the table is rebuilt cleanly every run; use Update instead if you only want to refresh changed rows.

‍

Break ties so the result is stable

If two orders share the same OrderDate (a date field without time, or two purchases in the same second), ROW_NUMBER() picks one arbitrarily. Tonight it returns order A, tomorrow order B, and your audience changes without any data change. Always add a unique column as the last ORDER BY key, here OrderID DESC.

Watch out for NULL dates too. In SQL Server, NULL sorts last in a DESC order, so empty dates fall to the bottom, which is usually what you want. If not, wrap the column in ISNULL() with a sentinel date.

‍

Narrow the input before you number it

A window function numbers every row that reaches it. On a transactional table with millions of rows, that ordering is the expensive part, and it is where a query drifts toward the 30-minute limit that Salesforce documents for query activities. Filter dates and statuses in the inner WHERE, not the outer one, so the engine sorts less.

On very large sources, split the work: one query activity writes a filtered staging data extension, a second applies ROW_NUMBER() to that smaller table.

‍

Deduplicate a data extension and keep the best row

‍

Deduplication is the same pattern with a different PARTITION BY: if duplicates are defined by email address, partition on EmailAddress. The real question is which duplicate survives, and marketers usually want the active record first, then the most recently modified.

A CASE WHEN inside the window's ORDER BY handles that priority without an extra join. For key strategy and the cleanup steps around it, see how to deduplicate contacts in SFMC.

SELECT
    SubscriberKey,
    EmailAddress,
    Status,
    LastModified
FROM (
    SELECT
        c.SubscriberKey,
        c.EmailAddress,
        c.Status,
        c.LastModified,
        ROW_NUMBER() OVER (
            PARTITION BY c.EmailAddress
            ORDER BY CASE WHEN c.Status = 'Active' THEN 0 ELSE 1 END,
                     c.LastModified DESC,
                     c.SubscriberKey
        ) AS rn
    FROM Customers_Import c
) AS deduped
WHERE rn = 1
  • PARTITION BY EmailAddress groups every row that shares an address.
  • The CASE expression returns 0 for Active rows and 1 for the rest, so Active always sorts first.
  • LastModified DESC then prefers the freshest record among rows with the same status.
  • SubscriberKey closes the sort as a unique tiebreaker.
  • The outer filter rn = 1 keeps one winner per address.

Target data extension: Customers_Master, primary key EmailAddress, data action Overwrite. If the target is sendable, relate SubscriberKey to the subscriber, otherwise sends fail even though the query succeeded.

‍

When MAX() with GROUP BY is enough

If you only need the latest date, MAX(OrderDate) with GROUP BY SubscriberKey is simpler and faster. ROW_NUMBER() earns its place when you need the other columns of the winning row: the order total, the product, the job ID.

‍

ROW_NUMBER vs RANK vs DENSE_RANK for top-N per subscriber

‍

All three functions share the same OVER (PARTITION BY ... ORDER BY ...) syntax and all three run in Marketing Cloud. They differ only in how they treat ties.

FunctionTiesSequence on 1, 1, 3Typical SFMC use
ROW_NUMBER()Broken arbitrarily unless a tiebreaker is added1, 2, 3Exactly one row per subscriber
RANK()Same number, next number skipped1, 1, 3Top 3 products including ties
DENSE_RANK()Same number, no gap1, 1, 2Tier levels without gaps

‍

Top 3 categories per subscriber

Window functions are evaluated after GROUP BY, so you can rank an aggregate directly. This returns each subscriber's three most purchased categories:

SELECT
    SubscriberKey,
    ProductCategory,
    PurchaseCount
FROM (
    SELECT
        p.SubscriberKey,
        p.ProductCategory,
        COUNT(*) AS PurchaseCount,
        ROW_NUMBER() OVER (
            PARTITION BY p.SubscriberKey
            ORDER BY COUNT(*) DESC, p.ProductCategory
        ) AS rn
    FROM Purchases p
    GROUP BY p.SubscriberKey, p.ProductCategory
) AS ranked
WHERE rn <= 3
  • GROUP BY collapses purchases to one row per subscriber and category, with COUNT(*) as the volume.
  • ROW_NUMBER() ranks those rows per subscriber, highest count first, category name as tiebreaker.
  • WHERE rn <= 3 keeps up to three rows per subscriber.

Target data extension: Top_Categories_Per_Subscriber, composite primary key on SubscriberKey and ProductCategory, data action Overwrite. Swap ROW_NUMBER() for RANK() if you would rather keep four rows when two categories tie for third place.

‍

Combine CASE WHEN and ROW_NUMBER() to build segments

‍

The last step is turning "latest record" into something a journey can use. A CASE WHEN in the outer query reads the winning row and assigns a label. Here the source is the _Open data view, which keeps about six months of tracking data, so the window is capped at 180 days:

SELECT
    SubscriberKey,
    LastOpenDate,
    LastOpenJobID,
    CASE
        WHEN DATEDIFF(DAY, LastOpenDate, GETDATE()) <= 30 THEN 'Hot'
        WHEN DATEDIFF(DAY, LastOpenDate, GETDATE()) <= 90 THEN 'Warm'
        ELSE 'Cold'
    END AS EngagementTier
FROM (
    SELECT
        o.SubscriberKey,
        o.EventDate AS LastOpenDate,
        o.JobID AS LastOpenJobID,
        ROW_NUMBER() OVER (
            PARTITION BY o.SubscriberKey
            ORDER BY o.EventDate DESC, o.JobID DESC
        ) AS rn
    FROM _Open o
    WHERE o.IsUnique = 1
      AND o.EventDate >= DATEADD(DAY, -180, GETDATE())
) AS lastopen
WHERE rn = 1
  • The inner query keeps only unique opens (IsUnique = 1) from the last 180 days.
  • ROW_NUMBER() ordered by EventDate DESC and JobID DESC finds each subscriber's most recent open and the job it came from.
  • The outer CASE converts the age of that open into Hot, Warm or Cold with DATEDIFF.
  • LastOpenJobID is carried along because the winning row is intact, which is the advantage over MAX().

Target data extension: Engagement_Tiers, primary key SubscriberKey, data action Overwrite, scheduled daily before the sends that depend on it. For local time zone boundaries, the SFMC SQL date functions guide covers the GETDATE() trap.

‍

Quick checklist before you save the query activity

‍

  1. Put ROW_NUMBER() in an inner SELECT and filter on its alias in the outer WHERE.
  2. Partition on SubscriberKey (or the field that defines a duplicate).
  3. End the window ORDER BY with a unique column so ties are stable.
  4. Filter dates and statuses inside the subquery, before the window runs.
  5. Match the target primary key to the partition key, and use Overwrite for one-row-per-key results.
  6. No WITH, no variables, no temp tables, no top-level ORDER BY without TOP.
  7. Run it once in a test automation and compare the row count to a COUNT(DISTINCT SubscriberKey) on the source.

If the activity still fails, the guide to common SFMC SQL errors maps each message to its fix.

‍

FAQ

‍

Does SFMC SQL support ROW_NUMBER()?

Yes. Query activities run a SQL Server dialect and accept ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), LAG() and LEAD(). The function must sit in the SELECT list of a subquery, never directly in a WHERE clause.

‍

How do I get the most recent record per subscriber in SFMC?

Number the rows with ROW_NUMBER() OVER (PARTITION BY SubscriberKey ORDER BY DateField DESC, UniqueID DESC) inside a subquery, then keep WHERE rn = 1 in the outer query. Write the result to a data extension whose primary key is SubscriberKey with the Overwrite action.

‍

Why does my query say windowed functions can only appear in the SELECT or ORDER BY clauses?

Because you referenced ROW_NUMBER() in a WHERE or HAVING clause. Move it to an inner SELECT with an alias, wrap that query as a derived table, and filter on the alias outside.

‍

Can I use a CTE (WITH) in a Marketing Cloud query activity?

No. Common table expressions, variables, temporary tables and cursors are not supported. Use nested subqueries in the FROM clause instead, or split the work into two query activities with a staging data extension in between.

‍

Build this audience in seconds with QAiry

‍

Every example above is a request a marketer can phrase in one sentence: the latest order per customer, one row per email, active first, top three categories per subscriber. QAiry turns that sentence into the subquery, the partition, the tiebreaker and the target data extension, inside your own Marketing Cloud account.

Install QAiry for free on your Business Unit, or watch the product demos to see a plain-language request become a production-ready query activity.

Share this article
QAiry for SFMC

Skip the SQL. Build segments by chatting.

QAiry turns plain English requests into Salesforce Marketing Cloud audience segments and data extensions — no SQL, no IT ticket, no waiting.

Built for SFMC · ISV Partner · GDPR-ready