MCE SQL Style Guide
Query with style. Readable, bug-free code is a few shifts & spaces away.20 min read
First things first: this Salesforce Marketing Cloud Engagement (MCE, formerly Salesforce Marketing Cloud) SQL style guide is highly subjective. You may use it as it is, implement only some parts of it, or ignore it altogether. There are only two rules that I believe are a must-have:
- Be consistent across your codebase.
- Strive for good readability.
Everything else is preference. And you are just about to learn about mine.
Letter Case
SQL gives you much freedom regarding the type of letter case you will be using for parts of your query. Let's use this freedom to create queries that are readable and aligned in convention to other MCE programmatic languages operating on the same data.
SQL Syntax Case
Use UPPERCASE for all elements of SQL syntax.
This approach helps visually differentiate query language from Tables (data extensions, data views) and Columns (fields) to improve readability.
/* ✅ Upper Case for SQL Syntax */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
WHERE DateJoined >= DATEADD(MONTH, -1, GETDATE())
/* ❌ Pascal Case for SQL Syntax */
Select
SubscriberKey
, EmailAddress
From Ent._Subscribers
Where DateJoined >= DateAdd(Month, -1, GetDate())
/* ❌ Lower Case for SQL Syntax */
select
SubscriberKey
, EmailAddress
from Ent._Subscribers
where DateJoined >= dateadd(month, -1, getdate())
Column & Table Names Case
Use PascalCase for all Table and Column names.
Treat it as a soft recommendation, as it is highly connected to your organisation's conventions. If other connected systems are using a different style, it might be best to follow it in MCE.
It is especially true for Tables, as you might be using mixed convention leveraging lowercase, uppercase and underscores for Data Extension names. However, try not to use hyphens, as those will require you to use square brackets around the name and might interfere in query syntax highlighting, leading to worse readability.
The most popular SQL convention for Table and Column names is snake_case. However, in MCE, the Table and Column names will share the case between your queries and the User Interface. It is essential to make them as readable and human friendly as possible. Additionally, in many cases, you will also leverage those names in AMPScript and SSJS.
Due to the above, I believe PascalCase - especially for Column names - is the best choice for MCE SQL.
/* ✅ Pascal Case for Table and Column names */
SELECT
wel.SubscriberKey
, wel.EmailAddress
, o.EventDate AS OpenDate
FROM WelcomeCampaignSegment AS wel
INNER JOIN _Open AS o
ON o.SubscriberKey = wel.SubscriberKey
/* ✅ Pascal Case for Column names and custom consistent covention for Table names */
SELECT
wel.SubscriberKey
, wel.EmailAddress
, o.EventDate AS OpenDate
FROM WEL_WelcomeCampaignSegment_20201011_OTH AS wel
INNER JOIN _Open AS o
ON o.SubscriberKey = wel.SubscriberKey
/* ❌ Lower Case for Table and Column names */
SELECT
wel.subscriberkey
, wel.emailaddress
, o.eventdate AS opendate
FROM welcomecampaignsegment AS wel
INNER JOIN _open AS o
ON o.subscriberkey = wel.subscriberkey
/* ❌ Upper Case for Table and Column names */
SELECT
WEL.SUBSCRIBERKEY
, WEL.EMAILADDRESS
, O.EVENTDATE AS OPENDATE
FROM WELCOMECAMPAIGNSEGMENT AS WEL
INNER JOIN _OPEN AS O
ON O.SUBSCRIBERKEY = WEL.SUBSCRIBERKEY
If you want to make your Style Guide even safer, you can decide on writing all Columns and Table names in square brackets. Some of SQL's reserved keywords fail as plain names, such as AS Key, which stops the query with "Incorrect syntax near the keyword 'Key'.". Square brackets protect you from that. The cost, however, is much more characters and less readable queries.
SELECT
[wel].[SubscriberKey]
, [wel].[EmailAddress]
, [o].[EventDate] AS [OpenDate]
FROM [WelcomeCampaignSegment] AS [wel]
INNER JOIN [_Open] AS [o]
ON [o].[SubscriberKey] = [wel].[SubscriberKey]
Alignment and Indentation
SQL is very flexible when it comes to alignment and indentation of the query. Writing everything in one line creates a valid code that will run. But just because it is correct, it doesn't mean it is good. Generous use of new lines and indents has close to no impact on performance but a massive impact on readability. Enter and Space keys are your friends.
There are many styles out there, and I decided to follow those that merge good writing speed with excellent readability.
Single Information per Line
Limit information per line to one.
I recommend keeping one information per line, as it allows for much easier scanning. The four most important examples of this approach are:
- Each
SELECTColumn in a separate line - Each
WHEREcondition in a separate line - Each
CASEcondition in a separate line - Each
JOINandONrelationship in a separate line
/* ✅ Single information per line */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
AND o.IsUnique = 1
WHERE
1 = CASE
WHEN j.EmailName LIKE 'UPS_%' THEN 1
WHEN j.EmailName LIKE 'CRS_%' THEN 1
ELSE 0
END
/* ❌ Multiple pieces of information per line */
SELECT s.SubscriberKey AS SubscriberKey, j.EmailName AS EmailName, s.EventDate AS SentDate, j.DeliveredTime AS DeliveryDate, o.EventDate AS OpenDate
FROM _Sent AS s
LEFT JOIN _Job AS j ON j.JobID = s.JobID
LEFT JOIN _Open AS o ON o.JobID = s.JobID AND o.ListID = s.ListID AND o.BatchID = s.BatchID AND o.SubscriberID = s.SubscriberID AND o.IsUnique = 1
WHERE 1 = CASE WHEN j.EmailName LIKE 'UPS_%' THEN 1 WHEN j.EmailName LIKE 'CRS_%' THEN 1 ELSE 0 END
As you can see, the SELECT and WHERE keywords have their separate line to mark respective block starting. For readability reasons, I make an exception if there is only one Column or condition to be used:
/* ✅ Single Column in SELECT and single condition in WHERE lines */
SELECT SubscriberKey
FROM _Subscribers
WHERE Domain = 'mateuszdabrowski.pl'
/* ❌ Separate lines with single SELECT Column and WHERE condition */
SELECT
SubscriberKey
FROM _Subscribers
WHERE
Domain = 'mateuszdabrowski.pl'
If you are using DISTINCT or TOP, put it into the same line as SELECT. In such a case, even if you work on a single Column, move it to a separate row for better readability.
/* ✅ Single Column in SELECT and single condition in WHERE lines */
SELECT DISTINCT TOP 10
SubscriberKey
FROM ContenstSubmissions
/* ❌ Separate lines for single SELECT Column and WHERE condition */
SELECT DISTINCT TOP 10 SubscriberKey
FROM ContenstSubmissions
The same goes for GROUP BY and ORDER BY with more than one item. A list inside ROLLUP or CUBE gets one item per line as well, indented inside its parentheses:
/* ✅ One grouping item per line, inside ROLLUP too */
SELECT TOP 20 PERCENT
Domain
, DATEPART(YEAR, DateJoined) AS YearJoined
, COUNT(*) AS SubscriberCount
FROM _Subscribers
GROUP BY ROLLUP (
Domain
, DATEPART(YEAR, DateJoined)
)
ORDER BY COUNT(*) DESC
/* ❌ The whole ROLLUP list in one line */
SELECT TOP 20 PERCENT
Domain
, DATEPART(YEAR, DateJoined) AS YearJoined
, COUNT(*) AS SubscriberCount
FROM _Subscribers
GROUP BY ROLLUP (Domain, DATEPART(YEAR, DateJoined))
ORDER BY COUNT(*) DESC
There is one exception I make on purpose: rows of sample values. When I build a small table to test a query against, the first SELECT names the Columns as usual, and every next row goes in one UNION ALL SELECT line. That way, it reads like the table it stands for:
/* ✅ Sample rows, one per line */
SELECT
'anna-1042' AS SubscriberKey
, 'ORD-1042' AS OrderId
, 74.98 AS OrderTotal
UNION ALL SELECT 'anna-1042', 'ORD-1187', 24.99
UNION ALL SELECT 'ben-2077', 'ORD-1100', 59.00
UNION ALL SELECT 'chloe-3101', 'ORD-1199', 210.00
Left Aligned Keywords
Align main SQL keywords to the left.
This rule focuses on writing speed. While I prefer the Vertically Aligned Space approach's aesthetics, I don't see any significant readability gains. On the other hand, writing in this style in MCE is a pain, as there is no autoformatter supporting it in Query Activity. The Format button in my SQL Studio (a free SQL editor that runs inside your own MCE account) follows this guide, so it will not add them either. We would have to add all those additional spaces manually. It's just not worth it.
/* ✅ Left Aligned Keywords */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
WHERE DateJoined >= DATEADD(MONTH, -1, GETDATE())
/* ❌ Post Keyword Space Aligned Vertically */
SELECT SubscriberKey,
EmailAddress
FROM Ent._Subscribers
WHERE DateJoined >= DATEADD(MONTH, -1, GETDATE())
Consistent Indentation
Use indentation to highlight SQL keyword relationships.
This rule focuses on readability. The logic, in short, is to indent whenever the line is dependent on the previous line (child line), for example:
- Selected Column Names are children of
SELECT JOINkeywords are children of the initial Table referenced withFROM- Joining relationships (
ON) are children ofJOIN - Case conditions are children of the
CASE - Where conditions are children of the
WHERE - Sub-queries follow the same rules in respective indentation level.
For simplicity I use 4-spaces indent, as it is both standard and can be added in MCE Query with a single click of the Tab key.
/* ✅ Dependency based indentation */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
AND o.IsUnique = 1
WHERE
1 = CASE
WHEN j.EmailName LIKE 'UPS_%' THEN 1
WHEN j.EmailName LIKE 'CRS_%' THEN 1
ELSE 0
END
/* ❌ Lack of indentation */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
FROM _Sent AS s
LEFT JOIN _Job AS j ON j.JobID = s.JobID
LEFT JOIN _Open AS o ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
AND o.IsUnique = 1
WHERE 1 = CASE
WHEN j.EmailName LIKE 'UPS_%' THEN 1
WHEN j.EmailName LIKE 'CRS_%' THEN 1
ELSE 0
END
Intentional Spacing
Use spaces wherever it makes the query more readable.
The must-have is spacing around any operators (equality or comparison) and after commas.
However, there is another place where spacing is beneficial for readability but might require an exception in some scenarios. Spacing for aliases and THEN keywords of the CASE statement.
I try to use it whenever possible, but when there is huge imbalance in length (for example one Column requires multi-function calculation or there is a single complex WHEN in CASE) equal spacing might make the query harder to read. Always decide which approach works best for your query from readability perspective.
When you equalize aliases or THEN keywords, put them at the first tab stop after the longest line. With the 4-spaces indent, it is exactly where a single press of the Tab key at the end of that line takes you, so you get the alignment without counting spaces. Do the same with Table aliases in FROM and JOIN, but treat them as a separate group with its own longest line. The ON lines do not count, as they carry no alias.
/* ✅ Spacing around operators plus equalizing aliases and THEN */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
AND o.IsUnique = 1
WHERE
1 = CASE
WHEN j.EmailName LIKE 'UPS_%' THEN 1
WHEN j.EmailName LIKE 'CRS_%' THEN 1
WHEN j.EmailName = 'OTH_SeedList' THEN 1
ELSE 0
END
/* ✅ Spacing around operators plus equalizing aliases with exceptions */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
, DATEDIFF(HOUR, s.EventDate, o.EventDate) AS TimeToOpen
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
AND o.IsUnique = 1
WHERE
1 = CASE
WHEN j.EmailName LIKE 'UPS_%' OR j.EmailName LIKE 'CRS_%' THEN 1
WHEN j.EmailName = 'OTH_SeedList' THEN 1
ELSE 0
END
/* ❌ Lack of spacing */
SELECT
s.SubscriberKey AS SubscriberKey
,j.EmailName AS EmailName
,s.EventDate AS SentDate
,j.DeliveredTime AS DeliveryDate
,o.EventDate AS OpenDate
,DATEDIFF(HOUR,s.EventDate,o.EventDate) AS TimeToOpen
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID=s.JobID
LEFT JOIN _Open AS o
ON o.JobID=s.JobID
AND o.ListID=s.ListID
AND o.BatchID=s.BatchID
AND o.SubscriberID=s.SubscriberID
AND o.IsUnique=1
WHERE
1=CASE
WHEN j.EmailName LIKE 'UPS_%' THEN 1
WHEN j.EmailName LIKE 'CRS_%' THEN 1
WHEN j.EmailName='OTH_SeedList' THEN 1
ELSE 0
END
Comments at the end of the lines follow the same rule, exception included. When two or more lines of the select list carry one, put them all at the first tab stop after the longest of those lines, so they read as one more column. If one of those lines is far longer than the rest, leave its comment one space after it, and align the others:
/* ✅ Equalized comments at the end of the lines */
SELECT
ISJSON('{"orderId":"ORD-1042"}') AS IsCompleteJsonValid /* Output: 1 */
, ISJSON('{"orderId":"ORD-1042"') AS IsBrokenJsonValid /* Output: 0 */
/* ❌ Comments one space after each line */
SELECT
ISJSON('{"orderId":"ORD-1042"}') AS IsCompleteJsonValid /* Output: 1 */
, ISJSON('{"orderId":"ORD-1042"') AS IsBrokenJsonValid /* Output: 0 */
Blank Lines
Use blank lines to separate the parts of a query that stand on their own.
Within a single query, I keep the lines together, as the indentation already shows its structure. A blank line helps in two places only.
The first is around UNION, UNION ALL, INTERSECT and EXCEPT. Each query they put together keeps its own block, so you can see at a glance where one ends and the next one starts. Rows of sample values are the exception again, as they read better as one table.
/* ✅ Blank lines around UNION ALL */
SELECT
SubscriberKey
, EmailAddress
FROM JanuaryEventParticipantsSegment
UNION ALL
SELECT
SubscriberKey
, EmailAddress
FROM FebruaryEventParticipantsSegment
/* ❌ UNION ALL squeezed between the queries */
SELECT
SubscriberKey
, EmailAddress
FROM JanuaryEventParticipantsSegment
UNION ALL
SELECT
SubscriberKey
, EmailAddress
FROM FebruaryEventParticipantsSegment
The second is before a comment of several lines that closes the query, like the Output block I add under examples. A one-line comment at the end stays right under the query.
/* ✅ Blank line before a closing comment block */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
WHERE Domain = 'example.com'
/* Output:
SubscriberKey | EmailAddress
anna-1042 | anna@example.com
*/
Commas Placement
Use commas at the beginning of the line.
There are few approaches related to comma placement. Initially, I favoured commas at the end of the line, as I found them more accessible to use due to their similarity to natural language. However, there are strong reasons to use the comma at the beginning of the line. Here is what convinced me to change my style:
- Adding or deleting a Column requires a change in only one line. It's easier, faster and minimises the risk of a crash due to the trailing comma.
- Above is also very beneficial during difference checking and when leveraging git for query version control. With a comma at the beginning of the line, the Column addition or deletion is displayed correctly as a single line change.
- Having a comma in the beginning makes it easier to assess where a new Column definition starts quickly. It is a vast readability improvement when you are using more complex structures, like
CASEinSELECT. - It's also easier to quickly assess whether you have a comma for each Column. With lines of various length, it is much harder with the comma at the end.
For the sake of readability, I indent the first Column by two spaces so that it is in line with the following ones. Similarly, I indent END after CASE in SELECT by two spaces for the same reason.
/* ✅ Commas at the beginning */
SELECT
SubscriberKey
, EmailAddress
, DateJoined
FROM Ent._Subscribers
/* ❌ Commas in the end */
SELECT
SubscriberKey,
EmailAddress,
DateJoined
FROM Ent._Subscribers
Explicit vs Implicit
Many things in SQL can be done in multiple ways - using various functions, symbols or shortcuts. While all those options may work, not all are a good idea. Whenever you are choosing the approach, go for the explicit and straightforward. Even if it means writing a few characters more.
Date Parts
Use full Date Parts names.
Yes, abbreviations let you save few characters, but they kill the readability unless someone is fluent in those shortcuts. For MCE purposes, the time saved during writing is not worth the time lost when reading. Go with the full version.
/* ✅ Full Date Part */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
WHERE DateJoined >= DATEADD(MONTH, -1, GETDATE())
/* ❌ Abbreviated Date Part */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
WHERE DateJoined >= DATEADD(M, -1, GETDATE())
JOIN and ON
Use INNER JOIN name and reference Column from the new Table first after ON.
Instead of just JOIN, write INNER JOIN - it's longer but explicit and in line with the rest of JOIN keywords. It makes it easier to scan queries with multiple various JOIN statements.
Additionally, when defining JOIN relationships after ON, firstly reference the Column from the joined Table. The previous Table should be on the right side. It will improve consistency and reading speed.
/* ✅ Explicit Inner Join and Column from new Table on the left side of the ON condition */
SELECT
wel.SubscriberKey
, wel.EmailAddress
, o.EventDate AS OpenDate
FROM WelcomeCampaignSegment AS wel
INNER JOIN _Open AS o
ON o.SubscriberKey = wel.SubscriberKey
/* ❌ Implicit Inner Join and Column from new Table on the right side of the ON condition */
SELECT
wel.SubscriberKey
, wel.EmailAddress
, o.EventDate AS OpenDate
FROM WelcomeCampaignSegment AS wel
JOIN _Open AS o
ON wel.SubscriberKey = o.SubscriberKey
Table Aliases
When using JOIN, add meaningful aliases for Tables and prefix all Columns with them.
There are a few points:
- If you are working on only one Table without
JOIN- don't use aliases at all. They are not needed and would make the query less readable. - If you have any
JOIN- always use aliases and prefixes. SQL doesn't always require it, but it is much easier to read the query when the Columns have an explicit Table mention in the prefix. - When you create an alias for a Table, make it meaningful. Using subsequent letters of the alphabet is not a good idea. Instead, use something that will remind the reader of the full name - for example, abbreviation using the first letter of each word in the Table. It will allow for much easier reading.
- Always use
ASkeyword between the Table name and the alias.
/* ✅ No aliasing in single Table query */
SELECT
SubscriberKey
, EmailAddress
FROM Ent._Subscribers
/* ❌ Aliasing in single Table query */
SELECT
s.SubscriberKey
, s.EmailAddress
FROM Ent._Subscribers AS s
/* ✅ Meaningful aliasing and prefixes in multi Table query */
SELECT
wel.SubscriberKey
, wel.EmailAddress
, o.EventDate AS OpenDate
FROM WelcomeCampaignSegment AS wel
INNER JOIN _Open AS o
ON o.SubscriberKey = wel.SubscriberKey
/* ❌ No aliasing and no prefix in multi Table query */
SELECT
SubscriberKey
, EmailAddress
, EventDate AS OpenDate
FROM WelcomeCampaignSegment
INNER JOIN _Open
ON _Open.SubscriberKey = WelcomeCampaignSegment.SubscriberKey
/* ❌ Not meaningful aliasing and no AS keyword in multi Table query */
SELECT
a.SubscriberKey
, a.EmailAddress
, b.EventDate AS OpenDate
FROM WelcomeCampaignSegment a
INNER JOIN _Open b
ON a.SubscriberKey = b.SubscriberKey
Not Equal To Symbol
Use != instead of <>.
The != symbol is much more popular and used in many languages. Using it makes the query more readable to people not experienced in SQL.
/* ✅ Use of != for negation */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE CONVERT(DATE, DateJoined) != CONVERT(DATE, GETDATE())
/* ❌ Use of <> for negation */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE CONVERT(DATE, DateJoined) <> CONVERT(DATE, GETDATE())
Meaningful Column Names
Use Column names that suggest the data type.
Just as with a letter case, you might have your hands tied by cross-system dependencies. But whenever possible, strive for meaningful names:
- Use descriptive Column names. It is better to have a long explicit one (
IsTrackingSuppressed) than a short mysterious abbreviation (trk). - When the Column is a boolean, prefix it with
Is(orHas/Doesdepending on the underlying data). - When the Column is a date, suffix it with
Date.
/* ✅ Meaningful and consistent Column Names */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryDate
, o.EventDate AS OpenDate
, j.SuppressTracking AS IsTrackingSuppressed
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
/* ❌ No consistency and type alignment in Column Names */
SELECT
s.SubscriberKey AS SubscriberKey
, j.EmailName AS EmailName
, s.EventDate AS SentDate
, j.DeliveredTime AS DeliveryTime
, o.EventDate AS OpenedAt
, j.SuppressTracking AS SuppressTracking
FROM _Sent AS s
LEFT JOIN _Job AS j
ON j.JobID = s.JobID
LEFT JOIN _Open AS o
ON o.JobID = s.JobID
AND o.ListID = s.ListID
AND o.BatchID = s.BatchID
AND o.SubscriberID = s.SubscriberID
Comments
Comments carry the context your query needs, like the reason behind a filter. However, MCE does not ignore everything inside them, and this can break your query.
Line Comments
Use block comments, never line comments.
A -- line comment looks harmless, and the syntax check passes it. However, when MCE saves your query as a Query Activity, which my SQL Studio also does behind every run, the comment no longer ends with its line. Everything after it is commented out, down to the end of the query. What breaks depends on where the comment sits:
- In the middle of the query, it comments out the rest of the query,
FROMincluded. The save fails with an error about a Column that has nothing wrong with it, like "Invalid column name 'SubscriberKey'" or "The multi-part identifier "s.SubscriberKey" could not be bound". - Before
SELECT, it comments out the whole query, and the save fails with "Cannot find table 0." - At the very end, the save goes through, but the run fails without any reason given. Pressing Enter after the comment does not help.
In my tests, a comment in the middle of the query failed the same way in Automation Studio and through the API. Block comments, /* */, have none of these problems, so I use them everywhere, even for a quick note at the end of a line.
/* ✅ Block comment */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl' /* skip internal test addresses */
/* ❌ Line comment in the middle comments out the rest of the query at the save */
SELECT SubscriberKey -- every subscriber but the internal ones
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl'
/* ❌ Line comment at the end fails the run */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl' -- skip internal test addresses
Apostrophes in Comments
Leave apostrophes out of comments.
MCE adds the N prefix to every text value in your query on its own. To find those values, it looks for apostrophes, and it does not skip comments. That leaves you with two traps:
- A single apostrophe in a comment, like the one in
don't, leaves an apostrophe without a pair. The syntax check passes, but saving the query fails with an error that points you somewhere else entirely: "Error while processing square brackets". It happens in--line comments as well. - Apostrophes in two different comments pair up with each other across your query, so it saves and runs. However, the
Nthen lands inside your text values. In my test, a query with/* it's a test */both above and belowSELECT TOP 1 'a' AS AreturnedaNinstead ofa.
A pair inside a single comment, like /* Output: 'MATEUSZ' */ in my examples, is safe, as it closes before the comment ends. Still, a comment with no apostrophes is the only kind you do not have to think about.
/* ✅ No apostrophes in comments */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl' /* skip internal test addresses */
/* ❌ A single apostrophe in a comment fails the save */
SELECT SubscriberKey
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl' /* don't send to internal test addresses */
/* ❌ Single apostrophes in two comments change the text value between them */
SELECT SubscriberKey /* it's the first comment */
FROM Ent._Subscribers
WHERE EmailAddress NOT LIKE '%@mateuszdabrowski.pl' /* and here's the second one */
Sum Up
It is a long article, so let's gather all the recommendations in one place:
- Be consistent
- Strive for readability
- Use comments to provide required context to your query
- Use block comments, never line comments 🔗
- Leave apostrophes out of comments 🔗
- Use
UPPERCASEfor SQL syntax 🔗 - Use
PascalCasefor Table & Column names 🔗 - Limit information per line to one 🔗
- Align main SQL keywords to the left 🔗
- Use indentation to highlight the relationship between SQL keywords 🔗
- Use spaces wherever it makes the query more readable 🔗
- Use blank lines to separate the parts of a query that stand on their own 🔗
- Use commas at the beginning of the line 🔗
- Use full Date Parts names 🔗
- Use
INNER JOINname overJOIN🔗 - In
JOIN ONreference Column from newly joined Table on the left 🔗 - When using
JOIN, add meaningful aliases for Tables and prefix all Columns 🔗 - Always use
ASkeyword between the Table name and the alias 🔗 - Use
!=instead of<>🔗 - Use Column names that suggest the data type 🔗
If you want to share something I'm missing or have arguments for a different recommendation - let me know.
Looking for more MCE style? Check out my: