SQL Formatter
Professional SQL beautifier and parser. Formats raw queries for MySQL, PostgreSQL, and SQL Server with customizable indentation and keyword capitalization.
About
Code readability remains a primary factor in software maintainability. Database queries often become convoluted strings of text during application logging or rapid prototyping, making debugging a strenuous task. This tool parses raw Structured Query Language strings and reconstructs them into a structured format. It applies deterministic rules for indentation and capitalization, transforming a single-line blob into a vertically aligned script. This process aids developers in visualizing the logical flow of data retrieval operations, join conditions, and nested subqueries. The parser operates entirely within the browser client, ensuring that sensitive schema information or data values are never transmitted to external servers. Correct formatting reduces cognitive load when reviewing legacy code or optimizing query performance plans.
Formulas
The formatting engine conceptualizes the SQL string as a stream of tokens, categorized into specific sets for processing. Let T be the set of all valid tokens in the input string.
Where Delta is determined by the token type. If t ∈ OPEN_BLOCK (e.g., (, CASE), the indentation increments. If t ∈ CLOSE_BLOCK (e.g., ), END), it decrements. The readability score R is optimized by minimizing line length L while maximizing vertical alignment.
Here, d represents the depth of the Abstract Syntax Tree (AST) node at index i.
Reference Data
| SQL Category | Keyword Examples | Standard Formatting Behavior |
|---|---|---|
| Data Query (DQL) | SELECT, FROM, WHERE | Starts a new line. Resets indentation level to base. acts as a primary block anchor. |
| Data Manipulation (DML) | INSERT, UPDATE, DELETE | Primary statement headers. often followed by INTO or SET on subsequent lines. |
| Joins & Relations | LEFT JOIN, INNER JOIN, ON | Indented relative to the FROM clause. conditions break to new lines for readability. |
| Logic Control | CASE, WHEN, THEN, ELSE | Triggers a nested indentation scope. END closes the scope and reduces indentation. |
| Set Operations | UNION, INTERSECT, EXCEPT | Treated as top-level separators between distinct query blocks. often surrounded by blank lines. |
| Grouping & Ordering | GROUP BY, ORDER BY, HAVING | Follows the WHERE clause hierarchy. typically aligns with the primary query keywords. |
| Data Definition (DDL) | CREATE, ALTER, DROP, TRUNCATE | Statement starters. column definitions inside (parentheses) are indented. |
| Transaction Control | COMMIT, ROLLBACK, SAVEPOINT | Standalone commands. usually zero indentation unless inside a stored procedure block. |