SQL Formatter: how it works and how to build one
Format messy SQL into readable, indented queries. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Puts each clause (SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY) on its own line, indents column lists and conditions, and upper-cases keywords. Strings and comments are left exactly as they are. Minify turns a query back into one line for logs or code.
When to use it
- Reading queries from logs or ORMs
- Code reviews
- Making long reports readable
How to use it
- Paste a query or open a .sql file.
- Choose Format or Minify and your keyword case.
- Copy or download the result.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/sql-formatter
How it works
SQL formatting is mostly about line breaks. The formatter first hides strings and comments so it never changes them, collapses all whitespace, then inserts a new line before each major clause (SELECT, FROM, JOIN, WHERE, GROUP BY…) and after commas in column lists.
Keywords are matched with a word-boundary regex and upper-cased. Finally the hidden strings and comments are put back.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
sqlFormat.ts (ts)
const CLAUSES = ["select", "from", "where", "group by", "order by", "having", "limit", "left join", "inner join", "join", "on", "union"];
export function formatSql(sql: string) {
const keep: string[] = [];
// 1. Protect strings and comments
let q = sql.replace(/'(?:''|[^'])*'|--[^\n]*/g, (m) => `\u0000${keep.push(m) - 1}\u0000`);
// 2. One line, then a break before each clause
q = q.replace(/\s+/g, " ").trim();
const re = new RegExp(`\\s*\\b(${CLAUSES.join("|").replace(/ /g, "\\s+")})\\b\\s*`, "gi");
q = q.replace(re, (_, k) => `\n${k.toUpperCase()}\n `);
q = q.replace(/,\s*/g, ",\n ").replace(/\s+\b(and|or)\b\s+/gi, (_, k) => `\n ${k.toUpperCase()} `);
// 3. Restore strings
return q.trim().replace(/\u0000(\d+)\u0000/g, (_, i) => keep[+i]);
}
Make it production-ready
- Keep function arguments like COUNT(a, b) on one line.
- Indent subqueries by their bracket depth.
- Add a dialect option for backtick or bracket identifiers.
Questions
Which databases does it support?
Standard SQL as used by PostgreSQL, MySQL, SQLite, SQL Server and BigQuery. It only changes whitespace and keyword case.
Free, runs in your browser, nothing is uploaded.