A T-SQL Formatting Style Guide for Teams

A query should reveal its joins and filters before a reviewer has to untangle its spacing. A shared formatting style makes that inspection easier and reduces arguments about how familiar code should look.

A row of music stands at the same height and angle, a hand straightening the one out of line

Write a Small Formatting Style Guide People Can Apply

Choose a few concrete rules for keyword case, indentation, column layout, commas, aliases, statement terminators, and comments. Keep the guide short enough that a contributor can apply it during an ordinary review. A document that tries to legislate every unusual syntax combination can become harder to navigate than the code it governs.

I favor a consistent readable baseline over a collection of personal preferences. Reviewers should be able to spot a changed filter or join without discussing the placement of every comma. Adopt one team convention, document a small exception process, and concentrate the review on data correctness and operational behavior.

The examples below use uppercase keywords, trailing commas, four-space indentation, explicit AS aliases, and semicolons. Those are proposed conventions rather than SQL Server requirements. Other consistent choices can work. A comma can attract more meeting time than the predicate whose meaning actually changes the result.

Keep the Sample Query and Data Contract Visible

Create a small temporary dataset so both formatting examples have the same source definitions. The customer key and order relationship are explicit, while the sample amounts and dates are synthetic inputs. They explain the query shape without claiming to represent an application's measured workload.

CREATE TABLE #Customer
(
    CustomerID int NOT NULL PRIMARY KEY,
    CustomerName nvarchar(60) NOT NULL
);
CREATE TABLE #CustomerOrder
(
    OrderID int NOT NULL PRIMARY KEY,
    CustomerID int NOT NULL,
    OrderDate date NOT NULL,
    Amount decimal(12,2) NOT NULL
);
INSERT #Customer VALUES (1,N'Sample Customer'),(2,N'Another Customer');
INSERT #CustomerOrder VALUES
    (101,1,'2026-09-01',20.00),
    (102,1,'2026-09-02',30.00),
    (103,2,'2026-09-03',15.00);

A formatting review should preserve the same selected columns, joins, filters, grouping, and ordering. Keep any semantic correction separate and explain it explicitly. Otherwise a supposedly cosmetic change can carry a hidden business change that reviewers overlook because the new layout looks cleaner.

Show the Dense Version Without Changing Its Meaning

The first query is intentionally crowded. Its lowercase keywords and optional aliases are legal, but the join, date filter, aggregation, and ordering require unnecessary visual work. A reader has to parse the entire line before finding the boundaries between those operations.

select c.CustomerID,c.CustomerName,sum(o.Amount) TotalAmount from #Customer c join #CustomerOrder o on o.CustomerID=c.CustomerID where o.OrderDate>='2026-09-01' and o.OrderDate<'2026-10-01' group by c.CustomerID,c.CustomerName order by c.CustomerID;

This example demonstrates readability, not a claim that lowercase keywords execute more slowly. The engine evaluates semantics and produces a plan; a keyword's visual case is not a performance setting. The audience benefiting from layout is the person reviewing, maintaining, and safely changing the statement.

Give Columns and Clauses a Clear Formatting Style

The reformatted query keeps one selected expression per line and places major clauses on their own lines. The join condition sits immediately below its JOIN. Filters align with AND, making an added or removed predicate easy to notice. GROUP BY and ORDER BY remain visible rather than hiding in the final part of a long sentence.

SELECT
    c.CustomerID,
    c.CustomerName,
    SUM(o.Amount) AS TotalAmount
FROM #Customer AS c
JOIN #CustomerOrder AS o
    ON o.CustomerID = c.CustomerID
WHERE o.OrderDate >= '2026-09-01'
    AND o.OrderDate < '2026-10-01'
GROUP BY
    c.CustomerID,
    c.CustomerName
ORDER BY
    c.CustomerID;

Choose the indentation depth once and apply it consistently to nested queries and related conditions. Keep parentheses where boolean grouping needs to be explicit. Spacing should expose precedence, but it cannot replace parentheses that determine the intended relationship between AND and OR conditions. Run both versions and they return the same two customer totals.

For wide statements, break a long expression at meaningful function or arithmetic boundaries. Keep short coherent expressions together when splitting them would make their meaning harder to follow. The guide should support comprehension rather than require a new line simply because a character counter reached an arbitrary number.

Same query, shorter review path: a diagram about the formatting style

Pick One Comma Convention and Use Explicit Aliases

Trailing commas keep punctuation beside the expression they terminate. Leading commas make added columns and accidental omissions visually distinctive. Either convention is valid when used consistently; mixing them within the same statement adds noise without improving the review. The following small selection illustrates the leading alternative.

SELECT
    o.OrderID
    , o.CustomerID
    , o.OrderDate
    , o.Amount
FROM #CustomerOrder AS o;

The proposed team baseline remains trailing commas. Document that choice rather than replaying the debate in each change. Use AS for result and table aliases, and give aliases stable meaningful names within the statement. Qualify columns in joins so their source remains clear when another table later gains a similar column.

Avoid reserved words for aliases or delimit them deliberately where a fixed contract requires them. A pleasant-looking label can still create a syntax error. Do not change externally consumed output names during formatting merely because the guide prefers another spelling.

Terminate Statements and Make CTE Boundaries Clear

Use semicolons consistently. They separate completed statements and remove ambiguity at syntax boundaries that require a preceding terminator. A CTE follows the WITH keyword, so a clearly terminated previous statement makes its role explicit. Do not rely on accidental surrounding batch structure to make the example compile.

DECLARE @MinimumAmount decimal(12,2) = 20.00;
WITH AcceptedOrders AS
(
    SELECT
        o.OrderID,
        o.CustomerID,
        o.Amount
    FROM #CustomerOrder AS o
    WHERE o.Amount >= @MinimumAmount
)
SELECT
    a.OrderID,
    a.CustomerID,
    a.Amount
FROM AcceptedOrders AS a;

Use GO only where a client batch boundary is intended, such as separating a module definition from its test call. It is a client batch separator rather than a T-SQL statement terminator. Keep module creation in its required independent batch, and do not insert GO where it would destroy the needed local-variable scope.

Write Comments That Explain Decisions

A useful comment explains a business boundary, a non-obvious assumption, or the reason for an unusual construct. A comment that repeats SELECT CustomerID in English adds little. Keep comments accurate after changes, and remove obsolete experimental fragments rather than turning them into an unreadable second implementation inside the file.

I review comments alongside predicates because an old explanation can make a newly changed query look safer than it is. Tie important assumptions to an accepted requirement or decision that reviewers can inspect. Avoid claims about measured performance unless the supporting test and workload are actually available.

Use short line comments near the relevant operation and a small header for purpose, parameters, and required context when needed. Do not fill every routine with a large historical diary. Keep durable change evidence in the accepted project process and let the code explain its current behavior clearly.

Keep Formatting Style Review Proportional to the Change

Which formatting style rule makes this statement easier to inspect? Apply that rule and verify that the formatting pass preserves semantics. Check string literals, quoted identifiers, aliases, and boolean grouping particularly carefully. A blanket case conversion can alter more than keywords if it is applied without language awareness.

Publish a compact example and a short agreed checklist, then use them consistently. Separate broad reformatting from a narrow functional change when the mixed difference would hide the important edit. Formatting style succeeds when reviewers spend less time decoding the statement and more time checking that it does the right work.

Related reading on this blog: Formatting T-SQL Consistently Across a Team and Naming Conventions for Tables, Columns and Constraints.

A style guide people can apply: a checklist on the formatting style

Formatting is not a correctness guarantee, it is a shared way to make the important parts of a query easier to review.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

Best Practices, SQL Coding Standards, SQL Scripts, SQL Server
Previous Post
SQL SERVER – How to Start SQL Server Service Without tempdb?
Next Post
SQL SERVER – Boosting User Experience with Analysis Services Perspectives – Notes from the Field #116

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.