SQL & Data

SQL Formatter

Paste a messy query and get clean, consistently indented SQL back: CTEs, joins, subqueries, CASE and window functions laid out so you can read them. Choose keyword case, indent and comma style for MySQL, PostgreSQL or standard SQL, or minify it to one line. Only whitespace and keyword case ever change.

Your SQL

One query or a whole script; separate statements with ;. Press Ctrl + Enter to format. Nothing leaves your browser.

Paste your SQL and press Format, or load the example.

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, SET and VALUES sit at the left of their query, with one item per line indented below. Short clauses such as LIMIT 10 and INSERT INTO orders (...) keep their content on the same line.
  • Joins sit under FROM. Each JOIN starts a line one level in, with its ON condition beside it. Extra conditions joined with AND go 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 AND inside BETWEEN 50000 AND 99999 stays put.
  • Brackets that hold a query open a new level: subqueries, CTE bodies, EXISTS (...) and IN (SELECT ...). Brackets that hold a list or a function call, such as IN ('Pune', 'Indore'), ROUND(x, 2) or a window’s OVER (PARTITION BY ... ORDER BY ...), stay on one line.
  • CASE reads like a table: each WHEN and the ELSE on its own line, END under CASE. A CASE inside a function call, such as SUM(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, recent and ranked, each become an indented block under WITH, and the final SELECT starts back at the left margin, so you can see at once that it reads from ranked.
  • 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 orders and customers through two CTEs, the second updates customers using orders.

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, not amount_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 WITH block 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.

Related learning on Codeayan

FAQ

SQL formatter questions

Can the formatter change what my query does?

No. It only changes whitespace (line breaks, indentation and spaces) and, if you ask, the letter case of SQL keywords. Every string, number, table name, column name, operator and comment comes out exactly as it went in and in the same order. The Checks tab proves this for your query: it re-reads the output and confirms the token stream is identical, and that formatting the output again changes nothing.

Is my SQL sent anywhere?

No. The tokenizer and formatter are plain JavaScript that run inside your browser tab. Nothing is uploaded, logged or stored, so it is safe to paste production queries, table names and customer filters. Opening a .sql file also reads it locally.

Which dialect should I choose?

Pick the database the query runs on. The dialect decides how quotes and comments are read: in MySQL, backticks quote names, double quotes are strings, backslashes escape quotes and # starts a comment. In PostgreSQL and standard SQL, double quotes quote names and # is an operator; PostgreSQL also has $$dollar quoted$$ strings and nested block comments. It also adds that dialect's keywords, such as AUTO_INCREMENT, REGEXP, ILIKE or RETURNING.

Why was a word like date or rank not uppercased?

Because it was being used as a name, not a keyword. Words such as date, year, rank or count are only treated as keywords where SQL uses them that way: rank() and count() before a bracket, DATE as a column type or in CAST(x AS DATE), DAY after INTERVAL 90. A column called date, anything after a dot (o.date) and every alias after AS keep the case you typed.

Leading or trailing commas: which is better?

Both are common. Trailing commas (a, b, c at the end of each line) read like normal text and are the default in most style guides. Leading commas (each new line starting with a comma) make it easy to comment out or reorder a column without touching the line above, which many analysts like for long SELECT lists. Pick one per team and keep it.

Will it fix errors in my SQL?

No, a formatter does not change tokens, so it never adds a missing comma or bracket. It does warn you about unbalanced brackets and unclosed strings or comments, and the indentation itself often shows the mistake: a clause that lands at the wrong depth usually means a bracket is in the wrong place.

More tools

Keep going