What this SQL formatter does
A query written in a hurry, copied out of a BI tool or generated by an ORM often arrives as one long line. This formatter reads it token by token, works out which words are SQL keywords and which are your own table and column names, and lays the query out so its structure is visible: each clause on its own line, its items indented underneath, every join on its own line and every subquery one level deeper than the query around it.
It handles single, double and backtick quotes with escaped quotes inside, --,
# and /* */ comments, CTEs (including WITH RECURSIVE), nested
subqueries, CASE WHEN, every JOIN form with ON or USING,
window functions, UNION, INTERSECT and EXCEPT,
INSERT, UPDATE, DELETE, CREATE TABLE and whole
scripts of several statements.
The layout rules
- Clauses start lines.
SELECT,FROM,WHERE,GROUP BY,HAVING,ORDER BY,SETandVALUESsit at the left of their query, with one item per line indented below. Short clauses such asLIMIT 10andINSERT INTO orders (...)keep their content on the same line. - Joins sit under FROM. Each JOIN starts a line one level in, with its
ONcondition beside it. Extra conditions joined withANDgo on the next line. - Conditions split at AND and OR in WHERE, HAVING and ON, so each filter is one line you can comment out. The
ANDinsideBETWEEN 50000 AND 99999stays put. - Brackets that hold a query open a new level: subqueries, CTE bodies,
EXISTS (...)andIN (SELECT ...). Brackets that hold a list or a function call, such asIN ('Pune', 'Indore'),ROUND(x, 2)or a window’sOVER (PARTITION BY ... ORDER BY ...), stay on one line. - CASE reads like a table: each
WHENand theELSEon its own line,ENDunderCASE. A CASE inside a function call, such asSUM(CASE WHEN ... END), stays on one line. - Statements are separated by a blank line. Comments stay where you put them: a comment at the end of a line stays at the end of that line, and a comment on its own line stays on its own line.
Worked example: top UPI spenders by city tier
Press Load example. The script has two statements typed in lowercase on a handful of long lines: a query with two CTEs that ranks customers by UPI spend in each city tier over the last 90 days, and an UPDATE that gives a loyalty badge to anyone who has spent ₹50,000 or more.
- The two CTEs,
recentandranked, each become an indented block underWITH, and the finalSELECTstarts back at the left margin, so you can see at once that it reads fromranked. - The
RANK() OVER (PARTITION BY c.city_tier ORDER BY SUM(r.amount_inr) DESC)window stays on one line, because breaking it would scatter one expression across five lines. - The CASE that turns spend into Gold, Silver and Bronze reads as three rules. The string
'Rahul''s pick: ₹50,000+'keeps its doubled quote and rupee sign exactly. - The Statements tab lists what each statement touches: the first reads
ordersandcustomersthrough two CTEs, the second updatescustomersusingorders.
Why you can trust the output
A formatter that rewrites a string literal or swallows a comment is worse than no formatter. This one is built around two guarantees, and checks both on every query you format (see the Checks tab):
- Token preservation. Splitting the output back into tokens gives exactly the token stream of your input: same strings, numbers, names, operators and comments, in the same order. Only keyword letter case may differ, and only if you chose UPPER or lower.
- Idempotence. Formatting the formatted output again changes nothing, so running it twice, or running it on SQL a teammate already formatted with the same settings, never creates a noisy diff.
Before release, both properties were tested on a corpus of over 30 deliberately awkward queries (escaped quotes, comments in odd places, nested CTEs, dollar quoting, every dialect and option), and the output was compared with the input after removing all whitespace.
Doing the same in Python
If you format SQL inside a data pipeline or notebook, the sqlparse library does a similar
job. Its layout differs a little from this tool’s, but the idea is the same:
import sqlparse
raw = "select o.order_id, c.full_name from orders o join customers c on c.customer_id = o.customer_id where o.paid_via = 'UPI'"
print(sqlparse.format(raw, reindent=True, keyword_case="upper", indent_width=2))
SQL style habits worth keeping
- Alias every table in a join and qualify every column (
o.amount_inr, notamount_inr). It costs a few characters and saves a debugging session when two tables share a column name. - Use CTEs for steps, not nested subqueries three deep. A
WITHblock reads top to bottom like a recipe; the formatter makes that structure obvious. - One condition per line in WHERE lets you switch filters off with
--while exploring data. - Do not rely on formatting to find bugs. A misplaced bracket shows up as odd indentation, but the formatter will not add a missing comma for you.