Formatting T-SQL Consistently Across a Team

The query logic is fine, but every file looks like a different language. Formatting T-SQL consistently helps a team review the rule instead of deciphering the layout.

A half-built brick wall with even mortar joints, a taut string line along the top and a trowel on the last brick.

Agree on a Small Readable Style for Formatting T-SQL

Choose indentation, keyword case, comma placement, alias style, and line length that the team can follow. The exact choice matters less than consistency. A style guide with five rules is more likely to be used than a long document about every possible SQL shape.

I start with examples from real team queries. A JOIN, CTE, window function, and UPDATE cover most disagreements. Show before and after versions, then ask whether the business logic is easier to see. The style should serve review.

Do not use formatting to hide a complicated query. A deeply nested expression can remain hard to understand with perfect indentation. Name logical steps and clarify grain when the structure itself is the problem.

SELECT o.OrderId,
       c.CustomerName,
       o.OrderDate
FROM dbo.Orders AS o
JOIN dbo.Customer AS c
  ON c.CustomerId = o.CustomerId
WHERE o.OrderStatus = 'Paid'
ORDER BY o.OrderDate, o.OrderId;

Make Joins and Predicates Visible

Put each JOIN and its ON condition where a reviewer can see the relationship. Separate join predicates from WHERE filters. That helps spot a missing key or a right-side filter that changes a LEFT JOIN into an effective INNER JOIN.

I prefer one important condition per line in a long WHERE clause. It makes a changed date boundary or tenant filter stand out. Short simple queries can stay compact. The goal is to show decisions, not maximize line count.

A formatter can align columns and keywords, but it cannot tell whether CustomerId is the right join key. Review still needs domain understanding. Consistent layout makes that review faster.

SELECT o.OrderId, c.CustomerName
FROM dbo.Orders AS o
LEFT JOIN dbo.Customer AS c
  ON c.CustomerId = o.CustomerId
WHERE o.OrderDate >= '2025-01-01'
  AND o.OrderDate < '2025-02-01';

Use a Formatter as a Tool

A formatter can apply agreed rules quickly and remove personal variation. Test it on representative T-SQL: CTEs, comments, dynamic SQL, window expressions, and long strings. Confirm that it preserves syntax and intended layout. Formatting T-SQL is not a substitute for running tests.

I review the formatter’s diff before accepting it. Some tools change case inside identifiers or rearrange comments in ways that hurt readability. Configure it for the team’s conventions and keep exceptions where a domain expression is clearer by hand.

The tool choice should fit the team’s editors and deployment path. A style nobody can apply in the normal workflow will not last. Start with a simple configuration and adjust only when repeated review pain appears.

WITH CustomerTotals AS
(
    SELECT CustomerId, SUM(OrderAmount) AS TotalAmount
    FROM dbo.Orders
    GROUP BY CustomerId
)
SELECT CustomerId, TotalAmount
FROM CustomerTotals
WHERE TotalAmount > 0;
How a small style reaches the code: a diagram about the formatting T-SQL

Do Not Reformat All History When Formatting T-SQL

A wholesale formatting change across old procedures can bury meaningful changes in thousands of modified lines. It can make incident review and comparison harder. Apply the style to new code and to sections being changed. Keep a separate planned cleanup only when it offers a clear benefit.

I ask reviewers to separate logic changes from formatting changes. A focused patch makes it easier to see whether a predicate, join, or transaction boundary changed. When a large file needs a format pass, do it independently and validate behavior before the next functional edit.

The history belongs to the team’s work record. Making it unreadable for the sake of visual uniformity is a poor trade. Consistency grows through new and touched code.

SELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name,
       OBJECT_NAME(object_id) AS module_name,
       modify_date
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC;

Keep Comments About Why While Formatting T-SQL

Comments should explain business decisions, edge cases, and safety assumptions. They need not narrate every SELECT and FROM. A comment such as “include the previous six days for the first rolling average” gives useful context. A comment saying “select rows” does not.

I put a short header on operational scripts that names target database, whether they write, parameters, and verification. Routine stored procedures need less ceremony, but tricky rules deserve a note near the expression they govern.

Formatting and comments should work together. Clear indentation shows the structure. A concise comment explains the reason. Neither can repair an incorrect result. Test the query after any meaningful rewrite.

-- Include the lookback before filtering the displayed month.
SELECT SalesDate, SalesAmount
FROM dbo.DailySales
WHERE SalesDate >= '2024-12-26'
  AND SalesDate < '2025-02-01';

Handle Generated and Dynamic SQL

Generated SQL can be hard to format by hand. Format the template that produces it, then inspect a representative generated statement. Keep whitespace predictable so logs and diagnostics are readable. Parameterize values and quote identifiers appropriately.

I do not use a formatter to solve dynamic SQL security. sp_executesql parameters and QUOTENAME have separate jobs. A beautifully indented concatenated string can still be unsafe. Keep formatting review and correctness review distinct.

For long generated statements, log a safe copy without secrets when support needs it. A consistent shape makes the statement easier to compare with a query plan. The output SQL is what SQL Server actually executes.

Make Review Easier, Not Louder

Pick a style that makes joins, filters, and transaction boundaries stand out. Apply it consistently in new work and touched areas. Give reviewers a short checklist, not a reason to spend the meeting debating comma placement.

I revisit the style only when repeated problems appear. If every new query needs an exception, the rule is too strict. If code remains hard to read, it is too vague. The team should be able to explain why each rule helps.

Formatting T-SQL is successful when a developer can open an unfamiliar procedure and find the business logic quickly. A formatter can help, but a stable small agreement does the real work.

Formatting rules should reduce review noise. Choose a small set that covers capitalization, indentation, JOIN placement, commas, and long predicates. Let a formatter apply the mechanical parts, then review the resulting query for meaning. Which rule actually helps someone spot a missing predicate? If a style choice only creates arguments, leave it out of the first standard.

I avoid reformatting years of untouched procedures in one change. That hides real edits in a wall of whitespace and makes deployment review harder. Apply the style to new code and to a module when it is already being changed. Document exceptions for generated SQL and code copied from a vendor so the team does not waste time polishing text it does not own.

Use the formatter’s configuration as a shared artifact and review changes to it. Two developers using different settings can create a noisy diff on every edit. I test the settings on a small, awkward procedure before applying them broadly.

Related reading on this blog: Driving up Database Coding Standards and Productivity with SQL Prompt and Why Should You Not to Use Old Style JOIN?.

Before the style becomes the rule: a checklist on the formatting T-SQL

Formatting is not a contest over whitespace, it is a shared way to make SQL decisions visible.

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

Best Practices, Software Development, SQL Coding Standards, SQL Server
Previous Post
SQL SERVER – An Interesting Case of Redundant Indexes – Index on Col1 and Included Columns Col2 and Col3 – Part 5
Next Post
Rehearsing a master Database Restore on a Test Instance

Related Posts

1 Comment. Leave new

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.