SQL Formatter
Format, beautify, and minify SQL instantly
Why Format SQL?
Raw SQL β especially when copied from an ORM output, a query planner, or a legacy codebase β is often a wall of text with no capitalisation, inconsistent spacing, and no line breaks. Formatted SQL makes the structure of a query immediately visible: which tables are joined, what conditions are filtered, what columns are selected. This matters for:
- Code reviews β formatted SQL shows structure at a glance instead of requiring a mental parse.
- Debugging β spotting a missing JOIN condition or WHERE clause is far easier with proper indentation.
- Documentation β queries included in wikis, runbooks, and README files should always be readable.
- Version control diffs β consistently formatted SQL produces cleaner diffs with fewer noise changes.
SQL Formatting Conventions
There is no single "official" SQL style guide, but a consensus has emerged around a few conventions:
- Keywords uppercase: SELECT, FROM, WHERE, JOIN, ON, GROUP BY, ORDER BY, etc. This visually separates language keywords from identifiers (table/column names).
- Identifier case: snake_case (user_id, order_date) is standard in most databases; PascalCase is common in some .NET/SQL Server environments.
- Commas at end vs. start of line: Both are common. End-of-line commas (col1,\ncol2) are traditional; start-of-line (col1\n,col2) makes it easy to comment out a line without touching the one above.
- Indentation: 2 or 4 spaces for sub-clauses, WHERE conditions, and JOIN conditions. Tabs are rare in SQL.
- CTEs over subqueries: WITH clauses (Common Table Expressions) are far more readable than deeply nested subqueries. Most modern databases support them.
SQL Query Anatomy
Understanding the six clauses of a standard SELECT query (in execution order, not write order):
- FROM / JOIN β determines the source data and how tables are combined.
- WHERE β filters rows before aggregation.
- GROUP BY β groups rows with identical values in the specified columns.
- HAVING β filters groups (like WHERE but applied after aggregation).
- SELECT β chooses columns and applies expressions. Despite appearing first in a query, it executes near last.
- ORDER BY / LIMIT β sorts and paginates the final result set.
Writing queries in this mental execution order (FROM β WHERE β GROUP BY β HAVING β SELECT β ORDER BY) often makes it easier to reason about what a complex query does.