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 errors and fixes

Duplicate primary keys, truncation, type mismatches, ORDER BY rules and timeouts — what causes them and how to fix each one.

Type
Article
Topic
Marketing Cloud
Reading time
4 min
Updated
Author
GeekMidst Team
Reviewed by
Site owner
Engineer working across monitors showing code, charts and monitoring dashboards

Query activities in Automation Studio write the result of a SELECT into a target data extension. Most failures come from a mismatch between what the query returns and what the target data extension accepts.

Checklist of six Marketing Cloud Query Activity errors and fixes: duplicate keys, truncation, type mismatches, ORDER BY without TOP, timeouts and data view retention
Most Query Activity failures come from a mismatch between what the SELECT returns and what the target data extension accepts. View full size

1. Duplicate primary key violations

If the target data extension has a primary key and your query returns two rows with the same key, the activity fails. Deduplicate inside the query with ROW_NUMBER().

sql
SELECT SubscriberKey, EmailAddress, LastPurchaseDate
FROM (
    SELECT
        o.SubscriberKey,
        o.EmailAddress,
        o.PurchaseDate AS LastPurchaseDate,
        ROW_NUMBER() OVER (PARTITION BY o.SubscriberKey ORDER BY o.PurchaseDate DESC) AS rn
    FROM [Orders] o
) x
WHERE x.rn = 1
Keep only the most recent row per subscriber

2. Truncation errors

A text value longer than the target field length causes an error. Either increase the field length in the target data extension or trim explicitly with LEFT(field, 100).

3. Data type mismatches

Writing text into a Date or Number field fails when a value cannot be converted. Use TRY_CONVERT or filter invalid rows before inserting.

4. ORDER BY without TOP

ORDER BY is only allowed together with TOP in the outer query. If you only need ordering to pick one row per key, use ROW_NUMBER() as shown above.

5. Timeouts

Query activities have a run-time limit (commonly cited as 30 minutes; check Salesforce Help for the current figure). Reduce scanned data with selective WHERE clauses, stage intermediate results in their own data extensions, and avoid joining large data views without a date filter.

6. Data views and retention

System data views such as _Sent, _Open and _Click hold a limited history (roughly six months). Copy what you need for long-term reporting into your own data extensions on a schedule. Data view timestamps are recorded in Central Standard Time (no daylight saving adjustment), so allow for that when you filter by date or compare with your own data.

7. NULL into a required field

If a target field is not nullable and the query returns NULL for it, the row cannot be written and the activity errors. This often happens after a LEFT JOIN, where unmatched rows bring back NULLs. Either make the field nullable, supply a default with ISNULL(field, 'Unknown') or COALESCE, or filter those rows out.

8. Column names that do not match the target

The query writes to target fields by column name, not by position. Alias every computed column (... AS LastPurchaseDate) so it matches a field in the target data extension exactly. A column without a matching field, or an unaliased expression, is a common reason a query that "looks right" fails validation.

9. Ambiguous columns in joins

When two joined tables share a column name, such as SubscriberKey, an unqualified reference is ambiguous. Give every table an alias and prefix every column with it.

10. Unsupported T-SQL

The query activity accepts a single SELECT statement based on SQL Server syntax. Procedural features such as variables (DECLARE), temporary tables, stored procedures and cursors are not available. If you need multi-step logic, split it into several query activities that write to staging data extensions and run them in sequence in one automation.

11. Names that need brackets or a prefix

Data extension names containing spaces or hyphens must be wrapped in square brackets: [Order Lines]. To query a shared data extension from a child business unit, use the ENT. prefix, for example ENT.Shared_Customers.

sql
SELECT s.SubscriberKey
FROM _Sent s
LEFT JOIN _Open o
    ON  o.SubscriberKey = s.SubscriberKey
    AND o.JobID = s.JobID
    AND o.IsUnique = 1
WHERE s.EventDate >= DATEADD(DAY, -30, GETDATE())
  AND o.SubscriberKey IS NULL
GROUP BY s.SubscriberKey
Example: subscribers sent an email in the last 30 days who did not open

This example shows several of the fixes together: aliases on every table, a date filter on the data view to limit how much is scanned, and GROUP BY so each subscriber appears once and a primary key on SubscriberKey in the target will not be violated.

Troubleshooting a failed run

  1. Open the automation's activity history and read the error message in full. It usually names the field or constraint involved.
  2. Run the query against a copy of the target data extension with no primary key and all fields nullable. If it succeeds, the problem is a constraint (key, length, type or required field), not the SQL itself.
  3. Check the copy for duplicates, over-long values and NULLs in fields the real target requires.
  4. If the query times out, measure how many rows each source contributes and add date filters or staging steps.
  5. Remember that Validate Syntax checks the statement, not the data, so a query can validate and still fail at run time.

Checklist before you run

  • Target data extension fields, lengths and types match the SELECT output
  • Primary keys are unique in the result
  • Update type (overwrite, update, append) is what you intend
  • Query tested against a sample data extension first
  • Every computed column has an alias that matches a target field
  • Required target fields cannot receive NULL
  • Data view queries have a date filter

For rendering the results in email, see AMPscript LookupRows vs LookupOrderedRows.

Workflow diagram

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

Workflow

Automation failure alerting

Open full size
Automation failure alertingA scheduled automation fails at one of its activities. The failure is detected by an error notification or a status check and the team is alerted. After triage, the run is restarted from the failed step if that is safe; otherwise the cause is fixed and partial data cleaned up first.Automation failure alertingAutomationStudioMonitoringOps teamData and configYesNoRun starts: Imports, queries, sends. A scheduled or file-triggered automation runs its steps in order. Each step depends on the one before, so one failure can leave later data stale.Run startsImports, queries,sendsActivity fails: Import, query or extract error. Typical causes are a missing or malformed file, a SQL error such as a primary key violation, or a timeout. Later steps in the run do not execute.Activity failsImport, query orextract errorFailure detected: Error notice or status check. Automation Studio can email a notification on error. A separate status check through the API also catches automations that never started at all.Failure detectedError notice or statuscheckTeam alerted: Email, chat or ticket. The alert goes to a shared address, chat channel or ticket queue rather than one person, so failures are seen even when someone is away.Team alertedEmail, chat or ticketTriage the error: Run history and messages. The team reads the activity error and run history, checks the source file or query, and works out exactly what ran before the failure.Triage the errorRun history andmessagesSafe to re-run now?. A re-run is safe when steps overwrite rather than append and no send has gone out yet. Otherwise a blind re-run can duplicate rows or emails.Safe to re-runnow?Fix the cause: Clean partial loads. Correct the file, query or configuration and remove any partially loaded rows, so the re-run starts from a clean state.Fix the causeClean partial loadsRestart the run: From failed step. Run only the failed step and the ones after it, rather than the whole chain, then let the normal schedule carry on.Restart the runFrom failed stepOn schedule: Counts checked. Row counts and target tables are checked after the re-run, and the incident is logged so that repeat failures show a pattern.On scheduleCounts checkedStartAlert or exceptionSystem or platformChannel or touchpointPerson or teamDecisionProcess stepEnd or outcomeOriginal 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. Run starts Automation StudioImports, queries, sends

    A scheduled or file-triggered automation runs its steps in order. Each step depends on the one before, so one failure can leave later data stale.

    Next: Activity fails

  2. Activity fails Automation StudioImport, query or extract error

    Typical causes are a missing or malformed file, a SQL error such as a primary key violation, or a timeout. Later steps in the run do not execute.

    Next: Failure detected

  3. Failure detected MonitoringError notice or status check

    Automation Studio can email a notification on error. A separate status check through the API also catches automations that never started at all.

    Next: Team alerted

  4. Team alerted Ops teamEmail, chat or ticket

    The alert goes to a shared address, chat channel or ticket queue rather than one person, so failures are seen even when someone is away.

    Next: Triage the error

  5. Triage the error Ops teamRun history and messages

    The team reads the activity error and run history, checks the source file or query, and works out exactly what ran before the failure.

    Next: Safe to re-run now?

  6. Safe to re-run now? Ops team

    A re-run is safe when steps overwrite rather than append and no send has gone out yet. Otherwise a blind re-run can duplicate rows or emails.

    Next: Yes: Restart the run; No: Fix the cause

  7. Fix the cause Data and configClean partial loads

    Correct the file, query or configuration and remove any partially loaded rows, so the re-run starts from a clean state.

    Next: Restart the run

  8. Restart the run Automation StudioFrom failed step

    Run only the failed step and the ones after it, rather than the whole chain, then let the normal schedule carry on.

    Next: On schedule

  9. On schedule Automation StudioCounts checked

    Row counts and target tables are checked after the re-run, and the incident is logged so that repeat failures show a pattern.

    End of the flow.

A scheduled automation fails at one of its activities. The failure is detected by an error notification or a status check and the team is alerted. After triage, the run is restarted from the failed step if that is safe; otherwise the cause is fixed and partial data cleaned up first. Original GeekMidst explanatory diagram; not an official Salesforce reference architecture.

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