ServicesSalesforce consultingArchitectureImplementationOrg health checkDevelopmentIntegrations and APIsData migrationTesting and QAManaged supportSpecialist supportMarketing Cloud auditDeliverability
SolutionsMarketing Cloud EngagementMarketing Cloud NextSalesforce + BrazeAccount EngagementData Cloud (Data 360)Identity resolutionInsights and segmentsAgentforce and AIMCP integrationsSales and Service CloudReal-time personalisationIntegration solutionsEnterprise AI integrationBy industry
ArchitectureSalesforce CRMData 360Salesforce + BrazeAgentforceCustomer 360API-led integrationEvent-drivenMCP host, client and serverIdentity and consentMCP securityData governanceCI/CD and releasesOur public MCP server
ResourcesEngineering journalDecision guidesSolution blueprintsSalesforce productsProjects and achievementsSales ROI calculatorWhere we workChecklists and templatesPlanning toolsReadiness assessmentGlossaryAbout GeekMidstOur approachOur expertiseContact
CompanyAbout GeekMidstOur approachDelivery methodologyTrust and evidenceProjectsAchievementsBook a consultationContactWhere we workSecurity and data
Book a Consultation

Marketing Cloud SQL development

Query Activities that build the right audience every time: correct keys, no silent duplicates, and run times that hold up as your data grows.

Developer circles repeated lines on two printed result lists as a stopwatch times a query on her laptop

In Marketing Cloud Engagement, most audiences are built by SQL. Query Activities in Automation Studio read data extensions and system data views, then write the results into a target data extension that a send or journey uses. The SQL is a subset of T-SQL with its own rules, and small mistakes have large consequences: a missing join condition doubles an audience, a wrong data action wipes a table, and a query that ran in seconds last year now times out.

GeekMidst writes, reviews and optimises Marketing Cloud SQL for teams that need their audience logic to be correct and explainable.

Where we help

  • Audience building. Segment logic that combines profile, purchase and engagement data, with clear inclusion and exclusion rules.
  • Deduplication. Picking one row per subscriber reliably using window functions instead of hoping the data is clean.
  • Engagement reporting. Queries against data views such as sent, open, click, bounce and unsubscribe to produce reporting tables.
  • Performance work. Rewriting slow queries, splitting large ones into staged steps and fixing primary key design on targets.
  • Error diagnosis. Working out why a query fails validation, errors at run time or returns unexpected row counts.

Example: one row per subscriber

A common need is the latest order per subscriber in the last 90 days. The query below uses ROW_NUMBER() inside a derived table to keep only the most recent row. It assumes a data extension Orders_DE with SubscriberKey, EmailAddress, OrderNumber and OrderDate, and a target data extension whose primary key is SubscriberKey. Treat it as a pattern to adapt, not production code.

sql
SELECT
    x.SubscriberKey,
    x.EmailAddress,
    x.OrderNumber,
    x.OrderDate AS LastOrderDate
FROM (
    SELECT
        o.SubscriberKey,
        o.EmailAddress,
        o.OrderNumber,
        o.OrderDate,
        ROW_NUMBER() OVER (
            PARTITION BY o.SubscriberKey
            ORDER BY o.OrderDate DESC
        ) AS rn
    FROM Orders_DE o
    WHERE o.OrderDate >= DATEADD(day, -90, GETDATE())
) x
WHERE x.rn = 1
Latest order per subscriber; run as a Query Activity with the Overwrite data action

Without the window function, a subscriber with two orders would produce two rows, and the query would fail on the target's primary key or keep only one of them unpredictably. Our article on deduplicating with ROW_NUMBER covers tie-breaking and other edge cases, and the Marketing Cloud SQL Cheat Sheet collects the syntax we use most. Queries usually run inside larger automations, which our Automation Studio services cover.

Developer writing segmentation queries at a standing desk beside a large monitor

Common problems and how we approach them

SymptomLikely causeOur fix
Primary key violationDuplicate keys in the result setDeduplicate with a window function or fix the join
Audience larger than expectedJoin on a non-unique fieldJoin on keys, check cardinality before and after
Query times outLarge scans, functions on filtered columnsStage the work, filter early, simplify predicates
Target unexpectedly emptyOverwrite action with a failed or empty sourceStaging table plus a verification step
Time-based logic off by hoursServer time zone differs from business time zoneConvert explicitly and document the assumption

How a SQL engagement runs

  1. 01

    Collect the logic

    We document each audience or report in plain language with your marketers, including exclusions and edge cases.

  2. 02

    Review the data

    We check keys, field types and row counts in the source data extensions and data views involved.

  3. 03

    Write and stage

    Queries are written to test targets first, with intermediate staging tables where logic is complex.

  4. 04

    Validate

    Results are reconciled against expected counts and spot-checked record by record with your team.

  5. 05

    Deploy and schedule

    Queries move into production automations with the right data action, step order and error notifications.

  6. 06

    Document

    Each query gets a header comment and an entry in the automation documentation.

Workflow diagram

Explore how the pieces fit together. Select a step to read what happens there.

Workflow

Automation Studio data pipeline

Open full size
Automation Studio data pipelineA source system drops a file on the Marketing Cloud SFTP, which starts a file drop automation. The file is imported to a staging data extension, SQL query activities build a sendable target, and a verification step checks the row count before the send. If the check fails the run stops, the team is notified, and the run is restarted after a fix.Automation Studio data pipelineSource systemAutomationStudioData extensionsOps teamYesNoRe-run after fixFile exported: CSV to Marketing Cloud SFTP. The source system exports a delimited file to the Marketing Cloud SFTP on a fixed schedule. Agree the file name, columns, encoding and delimiter in writing.File exportedCSV to MarketingCloud SFTPRun triggered: File drop, name pattern. A file drop automation starts when a matching file arrives, rather than at a guessed time, so a late file does not cause an empty or stale run.Run triggeredFile drop, namepatternImport activity: Into a staging DE. The import loads the file into a staging data extension. Type and length mismatches show up here as row errors, before any query runs.Import activityInto a staging DEStaging DE: Raw rows, replaced each run. Keeping raw rows apart from the sendable table means a bad file can be inspected and re-imported without touching live audiences.Staging DERaw rows, replacedeach runSQL query activities: Clean, dedupe, join. Query activities standardise values, remove duplicates with ROW_NUMBER and join reference data. Each query writes to its target with a deliberate update type.SQL queryactivitiesClean, dedupe, joinTarget DE: Sendable, keyed on contact. The final table has a primary key, a send relationship to Subscriber Key and only the fields the send needs, plus a data retention policy.Target DESendable, keyed oncontactRow count in range?. A verification activity checks the target row count against agreed limits and stops the automation if the data looks wrong, before anything is sent.Row count inrange?Send activity: Emails target DE. The send activity mails the verified audience. Because it runs last, a failed import or query never reaches subscribers.Send activityEmails target DERun complete: History recorded. The run finishes and tracking starts to arrive. Activity history shows the timing and outcome of each step for later checks.Run completeHistory recordedRun stopped: Error email to team. The verification stop and the automation error notification tell the team straight away, rather than someone noticing a missing send days later.Run stoppedError email to teamFix the cause: File or query, then check. The team corrects the source file or the query and checks the staging data. Overwrite imports and queries make the restart safe to repeat.Fix the causeFile or query, thencheckStartProcess stepDataDecisionChannel or touchpointEnd or outcomeAlert or exceptionPerson or teamOriginal GeekMidst explanatory diagram, not an official Salesforce reference.

Select any step in the diagram, or use Step through, to see what happens at that point and why.

Text version: every step in order
  1. File exported Source systemCSV to Marketing Cloud SFTP

    The source system exports a delimited file to the Marketing Cloud SFTP on a fixed schedule. Agree the file name, columns, encoding and delimiter in writing.

    Next: Run triggered

  2. Run triggered Automation StudioFile drop, name pattern

    A file drop automation starts when a matching file arrives, rather than at a guessed time, so a late file does not cause an empty or stale run.

    Next: Import activity

  3. Import activity Automation StudioInto a staging DE

    The import loads the file into a staging data extension. Type and length mismatches show up here as row errors, before any query runs.

    Next: Staging DE

  4. Staging DE Data extensionsRaw rows, replaced each run

    Keeping raw rows apart from the sendable table means a bad file can be inspected and re-imported without touching live audiences.

    Next: SQL query activities

  5. SQL query activities Automation StudioClean, dedupe, join

    Query activities standardise values, remove duplicates with ROW_NUMBER and join reference data. Each query writes to its target with a deliberate update type.

    Next: Target DE

  6. Target DE Data extensionsSendable, keyed on contact

    The final table has a primary key, a send relationship to Subscriber Key and only the fields the send needs, plus a data retention policy.

    Next: Row count in range?

  7. Row count in range? Automation Studio

    A verification activity checks the target row count against agreed limits and stops the automation if the data looks wrong, before anything is sent.

    Next: Yes: Send activity; No: Run stopped

  8. Send activity Automation StudioEmails target DE

    The send activity mails the verified audience. Because it runs last, a failed import or query never reaches subscribers.

    Next: Run complete

  9. Run complete Automation StudioHistory recorded

    The run finishes and tracking starts to arrive. Activity history shows the timing and outcome of each step for later checks.

    End of the flow.

  10. Run stopped Ops teamError email to team

    The verification stop and the automation error notification tell the team straight away, rather than someone noticing a missing send days later.

    Next: Fix the cause

  11. Fix the cause Ops teamFile or query, then check

    The team corrects the source file or the query and checks the staging data. Overwrite imports and queries make the restart safe to repeat.

    Next: Re-run after fix: Run triggered

A source system drops a file on the Marketing Cloud SFTP, which starts a file drop automation. The file is imported to a staging data extension, SQL query activities build a sendable target, and a verification step checks the row count before the send. If the check fails the run stops, the team is notified, and the run is restarted after a fix. Original GeekMidst explanatory diagram; not an official Salesforce reference architecture.

Questions we hear

Is Marketing Cloud SQL the same as SQL Server?
It is based on T-SQL but only a subset is supported, and it runs as Query Activities that write to a data extension. Some statements and features you may use elsewhere are not available.
How long can a query run?
Query Activities have a run-time limit. Check the current limit for your account in Salesforce Help and design large queries to stay well within it.
Can SQL read tracking data?
Yes, through system data views. Data views hold a limited rolling window of history, so we copy what you need for long-term reporting into your own data extensions.
Can you fix our failing queries?
Yes. Start with Marketing Cloud SQL Query Activity Errors for common causes, or send us the error and we will diagnose it.

Get your audience SQL reviewed

Send us the queries that are slow, failing or hard to trust, and we will suggest how to fix them.

Request a technical assessment →

Part of our Marketing Cloud work: Salesforce Marketing Cloud Consulting

Next step: Marketing Cloud SQL Development

  1. We read it A practitioner reads your message and replies by email.
  2. Short call We confirm goals, constraints and what success looks like.
  3. Written scope You get a scope and estimate before any work starts.

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