SQL queries over Data Views

The SQL Query activity in Automation Studio: what it reads, which SQL it supports, what each run does to the target table, and how it is scheduled.

A marketing team wants to know which clients did not open the last send. In Marketing Cloud Engagement that question is written in SQL (structured query language) and the answer is stored in another table. What can that query read, and what does each run do to the table that receives it?

What it reads and what it writes

The SQL Query activity retrieves and unifies data across data extensions and system data views. A data extension is a table that contains data you provide, the subject of the sibling page on Data Extensions; a data view is one of those that, in Help’s words, come “provided in the system”, and what each one holds is the subject of the Data Views page.

What it accepts is bounded by a single sentence of Help: only SELECT statements against data extensions or data views in the account, or in the parent account. Two consequences follow. If there is only SELECT, the statement writes nothing: the only thing written is the target table. And a query is the route Help documents for reading a data view, not necessarily the only one.

Where a query is built

It is built in Automation Studio, and the first step comes before the query: create the table that will receive the result. Then, in Activities, Create Activity and SQL Query: name, external key and description; the statement; Validate Syntax; the target table and the write mode; and save. It can then be launched from Activities or included in an automation.

One apparently cosmetic detail, with its exact scope: the columns of a data extension are not typed by hand, but added by double-clicking or dragging them from the dialog’s list, because typed by hand, Help says, the activity cannot identify which table they belong to.

The SQL Help documents

The SQL support is based on SQL Server 2016 but does not correspond to it exactly. That sentence is Help’s, and it is what makes the list worth keeping at hand.

Supported Not supported
Nested queries, UNION, JOIN, GROUP BY Variables, cursors and user-defined functions
IF and CASE Transactions and locking, GOTO, PRINT, EXEC and any sp_* stored procedure
“Most functions, including MIN and MAX” Temporary tables and common table expressions (CTE)
CAST and CONVERT TEXT and IMAGE functions, and open-ended comments such as --

And a prohibition on combining, not on constructing: a query cannot carry both a JOIN and a SELECT *. The alternative Help gives is to name every column.

Two warnings. The reference page forbids the -- comment and uses it in one of its sample queries, so this page shows none with comments. And the optimization article publishes a separate list of non-searchable arguments —OR, NOT, <, >, NOT EXISTS, NOT IN, NOT LIKE and functions operating on a column value— which it asks you not to use in a WHERE for speed. That list is not the list of unsupported constructs, which is the one above, and confusing them leads to rewriting queries that work.

They run at the READ UNCOMMITTED isolation level, equivalent to WITH (NOLOCK), so Help calls the NOLOCK hint unnecessary. And it publishes four more rules separately.

When writing the query What Help says
Naming tables By name, not by external key; with the ENT. prefix for one in the parent account of an enterprise environment or one shared in an Enterprise 2.0 account
Decimal fields A Decimal field used in a query does not come out as a decimal
Data views and Enterprise 2.0 business units Under that literal heading, Help says that only data extensions are accessible for queries written at the Enterprise 2.0 business unit. What a business unit is, and what Enterprise 2.0 is, the Business Units page explains
Primary key Do not go beyond 1,700 bytes in a table’s primary key field

That third row does not contradict the data views page: at the Enterprise 2.0 parent unit a query reaches data extensions, and the event data is queried in the sender’s account, which is where Help says to look for it.

What each run does to the target table

The first rule is about selection: the target table cannot be any of the ones the query uses. The second, the write mode, decides what survives.

Mode What it does when it runs Performance per Help
Append Adds the new data at the end; does not update what exists Best for event logs and cases where only the most recent data matters
Update Updates what matches and appends new data without a match The least performant, and it can extend the query considerably
Overwrite Deletes everything there was and replaces it with the new data The most performant for most cases

That Overwrite deletes is quoted; whether that deletion can be recovered is said by no source of this page. Help’s two 30-day windows cover deletions made by hand, and it is the Data Extensions page that cites them.

On the type side, Help asks that you join only columns of the same type, use that type consistently in the ones that match between source and target, keep row widths at 4,000 characters or fewer, and trim each length.

How it is scheduled and how long it can run

An activity runs standalone with Run Once from its row in Activities, and Help warns that doing so may affect customers if it sits inside a running automation. To have it run unattended, Help documents including it in an automation with its starting source: a schedule, the arrival of a file on the Enhanced FTP (file transfer protocol) or an external trigger.

Scheduling it means dragging Schedule to the first position on the canvas, configuring it and saving. And the step people forget: on save, the automation is paused until you activate it, with Active and Activate.

And two different limits.

Limit What it applies to
30 minutes The query: SQL Query activities time out after 30 minutes
24 hours The automation: one running for more than 24 hours stops on its own when the next scheduled occurrence begins

Before the limit come the recommendations. If a query consistently runs longer than 10 minutes, Help asks you to transform the data with a different tool, and the sentence that says so names “Salesforce Customer Data Platform”; that the same article writes “Salesforce Data 360” in another section, which is the current name, is this page’s observation. It also asks for one query per step and, since most automations run on the hour, for moving yours to 8:30, because concurrency, two processes touching the same data at once, can cause queries to fail or time out.

When it fails: what to check

The SQL Query activity is one of four with a detail page of its own: the Configuration tab for how it is set up and the Action Log tab for the run history with its error information. Its errors nearly all read as a mismatch between source and target, and the last two columns translate Help’s own, Meaning and Suggested Action.

Error What it means What Help suggests
Query failed: Timeout The query took too long to run Retry the activity or automation if the error is not typical; if it recurs, optimize the query
Primary key violation The source is missing a primary key, or has duplicate keys Add a primary key field in the source, group records by the target’s primary key, dedupe with window functions, or remove the primary key from the target
Conversion failed The source has an alphanumeric field and the target’s is numeric Update either the source or the target so the data types match
String or binary data would be truncated The source field is longer than the target’s Increase the target field length so it allows the same number of characters
Invalid column name A field in the source or the target was renamed or deleted Check for columns and fields that were changed or deleted
Invalid object name The source or the target was deleted, renamed or is unavailable Confirm that the source and destination data extensions exist
Query failed: Query not allowed Queries are not available for the account Open a support case in Salesforce Help
SQL Query activity cannot be executed at this time The database has a high volume of write activity Retry the activity or automation; if the error persists, open a support case

If it keeps failing, the system stops it.

How a SQL Query activity gets suspended and how it comes backA SQL Query activity is the Automation Studio activity that runs a query and stores the result in a table. Salesforce Help says that when that activity encounters a system error, or fails 24 consecutive times, it is suspended. While it is suspended, Help says it cannot be copied, added to an automation, or run once with Run Once. To find out why it is suspended you go to that query's Action Log, the tab that holds the run history with the error information, and read the error. Help says that after you edit and save the activity, it is restarted automatically. There is one exception the page body covers and the diagram does not: if the log error is Query activity was terminated, Help asks you not to modify the activity, because the system error resolves itself.System error or 24consecutive failuresThe activity issuspendedIt can't be copied,added or runAction Log:read the errorFix and save it:it restarts itself

One exception worth knowing before touching anything: if the log shows “Query activity was terminated”, Help asks you not to modify the activity, because that error resolves itself and re-enables it.

The automation containing it stops at different thresholds: it is deactivated when it fails at least 30 consecutive times and accumulates a 100% failure rate for at least 30 days. The contrast deserves attention: a system error suspends the query but does not count toward deactivating it. That is on for all accounts, cannot be turned off, and an inactive automation does not run until it is reactivated with Active on Workflow.

Example: the clients who did not open the quarterly report

A private bank sends a quarterly portfolio report by email and wants to prepare the next one with the clients who did not open the previous one. Its client identifier, a Text field, is the contact key, and contact key and subscriber key are the same value. The case is invented; this page orders the steps, not Help.

  1. Create the target table before the query: a standard data extension with the four fields it returns —the subscriber key in Text, the job identifier, the batch one and the date—. Which decisions about that table can no longer be undone is covered by the Data Extensions page.
  2. Write the statement below. Dragging does not help here: that rule is for data extension columns, and the two tables in this query are data views, which are reached by typing their names (the Data Views page has the detail).
  3. Replace MY_JOB_ID with the identifier of the quarter’s send, as its article asks.
  4. Check the volume: Help recommends this query for sends of fewer than 500,000 subscribers, and intermediate tables for larger ones.
  5. Choose the write mode. That article uses Overwrite, which leaves only the result of the last run.
  6. Validate, save and schedule: Validate Syntax, save and activate an automation. One caveat of this page’s own: the identifier from step 3 stays fixed, so every scheduled run repeats the same send until someone changes it.

The statement is the variation Help documents for those who did not open, copied literally.

SELECT DISTINCT s.subscriberkey,
                s.jobid,
                s.batchid,
                s.eventdate AS SendDate
FROM   [_sent] AS s
       LEFT JOIN [_open] o
              ON s.jobid = o.jobid
                 AND s.listid = o.listid
                 AND s.batchid = o.batchid
                 AND s.subscriberid = o.subscriberid
                 AND o.isunique = 1
WHERE  o.subscriberid IS NULL
       AND s.jobid = MY_JOB_ID

The example promises no more than its steps deliver: it leaves a table with the clients who did not open that send. Turning it into the audience of the next one is a different set of decisions, the sendability ones covered by the Data Extensions page. That its subscriberkey column carries the bank’s client identifier follows from the equivalence between contact key and subscriber key, and chaining them that way is this page’s reading. Check it before assuming it: the Data Views page records that Help describes that column, in some data views, as an alternate identifier that defaults to the value of the email address, so the table may end up holding email addresses. That tension belongs to that page, as does what _sent and _open hold.

When a SQL query, and when something else

The criterion in each row is Help’s; the split into rows is this page’s.

Situation What Help indicates
A clean, structured dataset with audiences already created The ideal case for a query
Unifying and segmenting a large dataset Your own internal data warehouse or, in the words of the cited sentence, “Salesforce Customer Data Platform”; not a query
Copying data from one table to another A data extension extract with an import activity, not a query
A query with several JOIN clauses that times out Stage it: several small queries into holding tables and a final one that unites them
A query that consistently runs longer than 10 minutes A different tool to transform the data
A table with too much data Split it into several related through foreign keys

Before production

  1. The target table exists, is none of the ones the query uses, and its write mode is chosen deliberately: Overwrite deletes what was there and this page does not know whether it can be recovered (see “What each run does to the target table”).
  2. The statement carries no construct from the right-hand column and no JOIN beside a SELECT * (see “The SQL Help documents”).
  3. Types match and the target’s lengths are no shorter (see the conversion and truncation rows of “When it fails: what to check”).
  4. The duration measured with both limits in view, one query per step, and a start time that is not on the hour (see “How it is scheduled and how long it can run”).
  5. The automation activated after saving it, and the Action Log located before you need it (see “When it fails: what to check”).

Official sources

Back to the knowledge base