Back to SQL Formatter
SQL Formatter Guide

AST-Based vs Regex SQL Formatters

SQL formatting is more than adding a newline before each keyword. This comparison explains why grammar-aware AST parsing is safer for nested queries and dialect-specific syntax, while simple regex cleanup still has a limited place.

Why regex formatting breaks at grammar boundaries

Regular expressions see text patterns, not the parse tree that gives SQL its meaning. A keyword inside a string, comment, nested subquery, JSON path, or quoted identifier can look identical to a keyword that controls the query structure.

That ambiguity grows across dialects. BigQuery pipe stages, PostgreSQL casts, Snowflake colon paths, ClickHouse aggregate combinators, and T-SQL bracketed identifiers all require token and grammar awareness before line breaks are chosen.

Syntax that needs token awareness
SELECT payload:customer.id::NUMBER, note
FROM raw_events
WHERE note = 'format FROM only outside this string';

What AST-based formatting provides

An AST parser identifies statements, expressions, clauses, identifiers, literals, and operators before the formatter decides how to lay them out. That lets it indent a nested SELECT without mistaking a subquery’s WHERE for the outer query’s WHERE, and preserve comments or quoted text as attached syntax.

AST output is not a license to rewrite SQL semantics. A good formatter uses the parsed structure to change presentation—spacing, casing, and line breaks—while keeping the author’s expressions and statement order intact.

  • Nested CTEs and subqueries retain their scope.
  • Dialect-specific operators remain attached to their operands.
  • Comments and string literals are not treated as executable keywords.
  • A diff gives the developer a final semantic review boundary.

When a regex formatter is enough

A small, controlled SQL fragment with no nesting or dialect-specific syntax may be acceptable for a quick visual cleanup. It becomes risky when the output is committed, shared across teams, or applied to production queries. For those workflows, choose a parser that understands the target dialect and inspect the resulting diff.

Continue with the formatter

Ready to format your SQL?

Choose a dialect, format a query, and review the result with a Git-style diff.

Open SQL Formatter