SQL Formatter

Posted by John Liu on Sunday, November 29, 2026

To format SQL query to your specific style, we can utilise combination of SQLFluff and Python code without built a SSM extension.

How the single-step pipeline works

  1. Step 1 (SQLFluff Python API): Formats your .sql file deterministically (casing, leading commas, ON breaks, CASE blocks)
  2. Step 2 (AST Join-Tree Indenter via sqlglot): Parses the FROM clause, checks which table alias each JOIN … ON references (e.g., LC references L, B references LC), and automatically indents that entire JOIN + ON block one tab deeper under its parent table.
  3. Step 3 (One-Click in SSMS): SSMS External Tools calls python format_my_sql.py “$(ItemPath)” via a keyboard shortcut (e.g., Ctrl + K, Ctrl + F), saves your query, formats it in ~0.3 seconds with zero LLM hallucination risk, and reloads it in SSMS.

Install SQLFluff

pip install sqlfluff, sqlglot

Create SQLFluff config file

Create a custom SQLFluff config file (.sqlfluff) suite your requirements. Place the file in yyour Windows user home folder (C:\Users\YourUsername.sqlfluff). SQLFluff automatically applies it to any .sql file you format anywhere on your machine.

This is my example config

[sqlfluff]
dialect = tsql
templater = raw
# Lines over 150 characters (including long WHEN...THEN lines) will wrap automatically
max_line_length = 150
# Only enforce layout, capitalization, and aliasing (zero query logic changes)
rules = layout,capitalisation,aliasing
# Exclude CP02 (capitalisation.identifiers) so PascalCase table/column names stay untouched
exclude_rules = CP02

[sqlfluff:indentation]
indent_unit = tab
tab_space_size = 4
indented_joins = True
indented_on = True
indented_on_contents = True
indented_using_on = True
# Keeps short WHEN...THEN on one line, and indents THEN one tab under WHEN when wrapped
indented_then = True
indented_then_contents = True

# Leading vs. trailing commas on new lines
[sqlfluff:layout:type:comma]
line_position = leading

# Put major clauses on their own lines
[sqlfluff:layout:type:select_clause]
line_position = alone

[sqlfluff:layout:type:from_clause]
line_position = alone

[sqlfluff:layout:type:where_clause]
line_position = alone

[sqlfluff:layout:type:on_clause]
line_position = alone

# Leading AND / OR on new lines inside WHERE and ON clauses
[sqlfluff:layout:type:binary_operator]
line_position = leading

# UPPERCASE keywords, functions, and data types
[sqlfluff:rules:capitalisation.keywords]
capitalisation_policy = upper

[sqlfluff:rules:capitalisation.functions]
capitalisation_policy = upper

[sqlfluff:rules:capitalisation.types]
capitalisation_policy = upper

# Keep PascalCase / camelCase table and column names untouched. Set to upper or lower if want one format
[sqlfluff:rules:capitalisation.identifiers]
capitalisation_policy = consistent

# Preserve T-SQL `Alias = Expression` assignment style
[sqlfluff:rules:aliasing.expression]
allow_scalar = True

# Indent formula one tab deeper when a T-SQL `Alias =` wraps to the next line
[sqlfluff:layout:type:alias_operator]
line_position = trailing

[sqlfluff:layout:type:assignment_operator]
line_position = trailing

# Allow implicit aliases. If requires explicit AS keyword, set to explicit
[sqlfluff:rules:aliasing.table]
aliasing = implicit

[sqlfluff:rules:aliasing.column]
aliasing = implicit

Create format_my_sql.py

Save the script below to C:\Users<YourUsername>\format_my_sql.py:

import re
import sys
from pathlib import Path
import sqlfluff
from sqlfluff.core import FluffConfig


def apply_nested_join_indent(sql):
    lines = sql.splitlines()
    join_start_re = re.compile(
        r"^\t((?:LEFT|RIGHT|FULL|INNER|CROSS)\s+(?:OUTER\s+)?JOIN|(?:OUTER|CROSS)\s+APPLY)\b",
        re.IGNORECASE,
    )
    end_from_re = re.compile(
        r"^(WHERE|GROUP\s+BY|HAVING|ORDER\s+BY|UNION|EXCEPT|INTERSECT|OPTION)\b",
        re.IGNORECASE,
    )

    # 1. Split FROM clause into base table block + individual JOIN/APPLY blocks
    in_from = False
    blocks = []
    current_block = None

    for line in lines:
        stripped = line.lstrip("\ufeff").strip()

        if re.match(r"^FROM\b", stripped, re.IGNORECASE) and not line.startswith("\t"):
            in_from = True
            current_block = {"type": "BASE", "lines": [line]}
            blocks.append(current_block)
            continue

        if in_from and end_from_re.match(stripped) and not line.startswith("\t"):
            in_from = False
            current_block = None
            blocks.append({"type": "OTHER", "lines": [line]})
            continue

        if in_from and join_start_re.match(line):
            current_block = {"type": "JOIN", "lines": [line]}
            blocks.append(current_block)
            continue

        if in_from and current_block is not None:
            current_block["lines"].append(line)
        else:
            blocks.append({"type": "OTHER", "lines": [line]})

    # 2. Extract table alias & parent references for each block to compute indent depth
    alias_depth = {}
    alias_re = re.compile(r"\b(?:AS\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*$", re.IGNORECASE)
    col_ref_re = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*(?:\[?[A-Za-z_][A-Za-z0-9_]*\]?)")

    for block in blocks:
        if block["type"] == "BASE":
            text = "\n".join(block["lines"])
            m = alias_re.search(text)
            if m:
                alias_depth[m.group(1).upper()] = 0

        elif block["type"] == "JOIN":
            join_lines = block["lines"]
            # Find the alias of this joined table / subquery
            target_alias = ""
            if "APPLY" in join_lines.pop(0) if False else re.search(r"\bAPPLY\b", next(iter(join_lines)), re.IGNORECASE):
                # For OUTER/CROSS APPLY, alias is on the closing `) Alias` line
                for ln in reversed(join_lines):
                    clean = re.sub(r"--.*$", "", ln).strip()
                    m = re.match(r"^\)\s*(?:AS\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*$", clean, re.IGNORECASE)
                    if m:
                        target_alias = m.group(1).upper()
                        break
            else:
                # For regular JOIN, alias is at the end of the table name line (before ON)
                for ln in join_lines:
                    clean = re.sub(r"--.*$", "", ln).strip()
                    if re.match(r"^ON\b", clean, re.IGNORECASE):
                        break
                    m = alias_re.search(clean)
                    if m and m.group(1).upper() not in ("JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "OUTER"):
                        target_alias = m.group(1).upper()

            # Find all Alias.Column references inside this JOIN/APPLY block
            refs = set()
            for ln in join_lines:
                clean = re.sub(r"--.*$", "", ln)
                for m in col_ref_re.finditer(clean):
                    ref = m.group(1).upper()
                    if ref != target_alias:
                        refs.add(ref)

            parent_depths = [alias_depth[r] for r in refs if r in alias_depth]
            depth = (max(parent_depths) + 1) if parent_depths else 0
            if target_alias:
                alias_depth[target_alias] = depth

            # Shift ON and its conditions 1 extra tab deeper under the joined table
            shifted_lines = []
            past_on = False
            for ln in join_lines:
                if re.match(r"^\t+ON\b", ln, re.IGNORECASE):
                    past_on = True
                extra = (depth - 1 if depth > 1 else 0) + (1 if past_on else 0)
                shifted_lines.append((("\t" * extra) + ln) if (extra > 0 and ln.strip()) else ln)
            block["lines"] = shifted_lines

    out_lines = []
    for block in blocks:
        out_lines.extend(block["lines"])

    return "\n".join(out_lines) + ("\n" if sql.endswith("\n") else "")


def apply_wrapped_alias_indent(sql):
    lines = sql.splitlines()
    out_lines = []
    indenting_alias = False
    base_tabs = 0

    for line in lines:
        stripped = line.strip()
        tabs = len(line) - len(line.lstrip("\t"))

        if indenting_alias:
            # Stop extra indent when the next SELECT column (, ...) or FROM/WHERE arrives
            if (stripped.startswith(",") and tabs <= base_tabs) or (tabs < base_tabs and stripped):
                indenting_alias = False
            elif stripped:
                out_lines.append("\t" + line)
                continue
            else:
                out_lines.append(line)
                continue

        # Detect a SELECT column line ending with `=` (ignoring trailing comments)
        code_only = re.sub(r"--.*$", "", line).rstrip()
        if code_only.endswith("=") and tabs >= 1:
            indenting_alias = True
            base_tabs = tabs

        out_lines.append(line)

    return "\n".join(out_lines) + ("\n" if sql.endswith("\n") else "")


def format_apply_subqueries(sql):
    # Collapses `(\n\tSELECT` inside APPLY blocks to `(SELECT` and shifts subquery body left 1 tab
    lines = sql.splitlines()
    out_lines = []
    in_apply_sub = False
    paren_tabs = 0

    for i, line in enumerate(lines):
        stripped = line.strip()
        tabs = len(line) - len(line.lstrip("\t"))

        if not in_apply_sub and stripped == "(" and i > 0 and re.search(r"\bAPPLY\b", lines[i - 1], re.IGNORECASE):
            in_apply_sub = True
            paren_tabs = tabs
            out_lines.append(line)
            continue

        if in_apply_sub:
            if stripped.startswith(")") and tabs == paren_tabs:
                in_apply_sub = False
                out_lines.append(line)
                continue
            if out_lines[-1].strip() == "(":
                out_lines[-1] = out_lines[-1] + stripped
                continue
            if line.startswith("\t" * (paren_tabs + 1)):
                out_lines.append(line[1:])
                continue

        out_lines.append(line)

    return "\n".join(out_lines) + ("\n" if sql.endswith("\n") else "")


def format_paren_conditions(sql):
    # Converts `AND (\n\t\tCond1\n\t\tOR Cond2\n\t)` into `AND (Cond1\n\t\tOR Cond2\n\t\t)`
    lines = sql.splitlines()
    out_lines = []
    in_paren = False
    open_tabs = 0

    for line in lines:
        stripped = line.strip()
        tabs = len(line) - len(line.lstrip("\t"))

        if not in_paren and re.match(r"^(?:AND|OR)\s*\($", stripped, re.IGNORECASE):
            in_paren = True
            open_tabs = tabs
            out_lines.append(line)
            continue

        if in_paren:
            # First line inside `AND (` -> pull onto the `AND (` line
            if re.match(r"^(?:AND|OR)\s*\($", out_lines[-1].strip(), re.IGNORECASE):
                out_lines[-1] = out_lines[-1] + stripped
                continue
            # Closing `)` -> align one tab deeper to match the conditions inside
            if stripped.startswith(")") and tabs == open_tabs:
                in_paren = False
                out_lines.append("\t" + line)
                continue

        out_lines.append(line)

    return "\n".join(out_lines) + ("\n" if sql.endswith("\n") else "")


def format_file(file_path):
    path = Path(file_path)
    # utf-8-sig automatically strips any BOM written by SSMS
    original_sql = path.read_text(encoding="utf-8-sig")

    config_file = Path.home() / ".sqlfluff"
    config = FluffConfig.from_path(str(config_file))

    fluffed_sql = sqlfluff.fix(original_sql, config=config)
    final_sql = format_paren_conditions(format_apply_subqueries(apply_wrapped_alias_indent(apply_nested_join_indent(fluffed_sql))))
    path.write_text(final_sql, encoding="utf-8")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python format_my_sql.py <path_to_sql_file>")
        sys.exit(1)
    format_file(sys.argv.pop(1))

Hook SQLFluff into SSMS

  1. Find your Python executable path by running where python in PowerShell
  2. Open SSMS and go to Tools > External Tools…
  3. Click Add and enter:
    • Title: Format My Query
    • Command: your Python executable path from step 1
    • Arguments: “C:\Users\YourUsername\format_my_sql.py” “$(ItemPath)”
    • Initial directory: $(ItemDir)
  4. Click Ok