Skip to content

SQL Formatter

Format and beautify SQL queries with proper indentation and keyword capitalisation.

Part of Dev Utils · Built by Sandeep Upadhyay

  • SQL query formatting
  • Multi-dialect support
  • Keyword capitalisation

When to use SQL Formatter

  • Cleaning up auto-generated queries: ORM-generated SQL output is often single-line and unreadable. Format it to understand exactly what query is being sent to the database.
  • Code review preparation: Format raw SQL before adding it to a pull request or migration file so reviewers can read the logic without deciphering minified syntax.
  • Debugging slow queries: Format a query before running EXPLAIN ANALYZE - readable formatting makes it easier to identify which JOIN or subquery is likely causing the performance issue.
  • Standardising SQL in a shared codebase: Use formatted output as the canonical style for SQL files committed to source control, ensuring consistent style across contributors.

How SQL formatting works across different SQL dialects

The SQL Formatter tokenises your raw SQL input into a stream of keywords, identifiers, operators, literals, and punctuation, then re-emits those tokens with consistent indentation and line breaks applied based on formatting rules. Keywords such as SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, and HAVING are placed on new lines and printed in uppercase. Subqueries and case expressions are indented one level deeper than their parent clause, and each item in a SELECT list is placed on its own line when the query has more than two columns.

The formatter handles four primary SQL dialects: standard ANSI SQL, PostgreSQL, MySQL, and T-SQL (Microsoft SQL Server). Dialect-specific syntax is preserved - PostgreSQL's :: casting operator, MySQL's backtick identifiers, and T-SQL's bracket identifiers are all tokenised correctly rather than treated as syntax errors. Comments (both -- single-line and /* multi-line */ styles) are preserved in their original position in the token stream.

The output is intentionally opinionated rather than configurable: all-uppercase keywords, consistent two-space indentation, and joins placed on their own lines. This matches the style enforced by popular SQL formatters used in database IDEs (DBeaver, DataGrip) and linters (sqlfluff). Formatted SQL is easier to read during code reviews, easier to diff in version control, and significantly easier to debug when a clause is producing unexpected results - you can see the exact WHERE conditions and JOIN paths at a glance.

Try SQL Formatter

Interactive SQL Formatter - coming soon