SQL Formatter
Format and beautify SQL queries with proper indentation and keyword highlighting.
Input SQL
Formatted SQL
SELECT u.id, u.name, u.email, o.order_id, o.total
FROM users u INNER
JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2024-01-01'
AND o.status = 'completed'
GROUP BY u.id, u.name, u.email, o.order_id, o.total
HAVING o.total > 100
ORDER BY o.total DESC
LIMIT 50;Supported SQL Statements
Tip: Well-formatted SQL is easier to read, debug, and maintain. Use consistent formatting across your team.
What Is SQL Formatting?
SQL formatting is the process of restructuring raw or minified SQL query text into a clean, human-readable layout by applying consistent indentation, line breaks, and keyword casing. Whether you're debugging a complex query, reviewing a teammate's code, or pasting a one-liner from an ORM log, a properly formatted SQL statement dramatically reduces the mental effort needed to parse its logic.
An unformatted SQL query might cram a SELECT, multiple JOIN clauses, a WHERE condition chain, and an ORDER BY all onto a single line. The SQL formatter breaks that wall of text into structured, clause-by-clause blocks so that each logical component of the query sits on its own line or a predictable indented continuation.
Good SQL formatting isn't just cosmetic. Teams that enforce a consistent SQL style catch logic errors faster during code review, write more maintainable migration scripts, and reduce the chance of accidentally hiding a runaway OR condition that bypasses a security check. The SQL Formatter tool automates this process with zero configuration required — paste your query, choose your indent size (2 or 4 spaces), and decide whether keywords should be uppercase or lowercase.
This tool supports the most common SQL statement types: SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, DROP, and ALTER. It also correctly handles multi-clause constructs like GROUP BY, ORDER BY, HAVING, UNION, UNION ALL, and all standard JOIN variants (INNER, LEFT, RIGHT, OUTER).
How the SQL Formatter Works
The SQL Formatter applies a deterministic, rule-based algorithm to your input text. Understanding the steps helps you predict exactly how your query will be rendered and troubleshoot any edge cases in unusual SQL syntax.
Step 1 — Whitespace normalization. The formatter first collapses all consecutive whitespace characters (spaces, tabs, newlines) into a single space. This means it doesn't matter whether your input is already partially indented or completely minified — the process always starts from a clean single-line representation.
Step 2 — Clause-level line breaks. The formatter inserts a newline before every major SQL clause keyword. These "newline keywords" include: SELECT, FROM, WHERE, AND, OR, JOIN, INNER JOIN, LEFT JOIN, RIGHT JOIN, OUTER JOIN, GROUP BY, ORDER BY, HAVING, LIMIT, UNION, UNION ALL, INSERT INTO, VALUES, UPDATE, SET, DELETE. The regex replacement is case-insensitive so it works regardless of how the original query was written.
Step 3 — Keyword casing. If the Uppercase keywords option is enabled (the default), every recognized SQL keyword is converted to uppercase using word-boundary-aware regex replacements. If disabled, all keywords are lowercased. This applies to the full keyword list including aggregate functions like COUNT, SUM, AVG, MAX, and MIN, as well as logical operators like NULL, NOT, IN, BETWEEN, LIKE, and EXISTS.
Step 4 — Continuation-line indentation. After splitting into lines, any line whose first token is AND, OR, or ON is prepended with the chosen indent (2 or 4 spaces). This visually groups WHERE condition chains and JOIN predicates under their parent clause, making multi-condition filters immediately legible.
Continuation Line Indentation Rule
Where:
- indentSize= Number of spaces per indent level (2 or 4, selected by user)
- line= A single output line whose first keyword is AND, OR, or ON
- ' '.repeat(indentSize)= A string of indentSize space characters prepended to the line
Supported SQL Keywords and Clauses
The formatter recognizes a comprehensive set of ANSI SQL keywords covering the four core DML statement types (SELECT, INSERT, UPDATE, DELETE), DDL statements (CREATE, DROP, ALTER), and a wide range of clause modifiers. Below is a structured overview of every keyword category the tool handles.
| Category | Keywords |
|---|---|
| Query clauses | SELECT, FROM, WHERE, GROUP BY, ORDER BY, HAVING, LIMIT, OFFSET, DISTINCT |
| Join types | JOIN, INNER JOIN, LEFT JOIN, RIGHT JOIN, OUTER JOIN, ON |
| Set operations | UNION, UNION ALL |
| DML statements | INSERT, INTO, VALUES, UPDATE, SET, DELETE |
| DDL statements | CREATE, TABLE, DROP, ALTER, INDEX |
| Conditional logic | CASE, WHEN, THEN, ELSE, END, AND, OR, NOT |
| Predicates | IN, BETWEEN, LIKE, IS, EXISTS, NULL |
| Aggregate functions | COUNT, SUM, AVG, MAX, MIN |
| Modifiers | AS, ASC, DESC |
The keyword matching uses word-boundary regex (\b) to avoid incorrectly transforming identifiers that happen to contain a keyword as a substring — for example, a table named orders will not have its embedded substring matched against OR.
SQL Formatting Standards and Style Guides
SQL does not have a single official formatting standard the way languages like Python (PEP 8) or Go (gofmt) do, but several widely-adopted conventions have emerged from major database vendors, open-source communities, and enterprise style guides. Understanding these conventions helps you choose the formatting options that align with your team's preferences.
Uppercase vs. lowercase keywords. The most debated choice in SQL style is keyword casing. The traditional convention — and still the default in most editors, linters, and documentation — is uppercase for all reserved words: SELECT, FROM, WHERE. This visually separates language-defined tokens from user-defined identifiers (table names, column names, aliases). A modern counter-trend favors all-lowercase for a quieter visual style and easier typing. Both approaches appear in professional codebases; the important rule is consistency within a project.
Indentation depth. Two-space and four-space indentation are both common in SQL. Four spaces are more prevalent in database-heavy environments (PL/pgSQL, T-SQL stored procedures) where deeply nested blocks benefit from clearer visual hierarchy. Two spaces are common in application code where SQL strings appear inline or in migration files alongside other code that uses two-space indentation.
Clause alignment. Some style guides right-align clause keywords (padding SELECT, FROM, WHERE to the same width) to form a "river" of column-aligned clause bodies. Others left-align every clause keyword at column zero. This formatter uses left-aligned clause keywords with indented continuation lines, which is the most widely understood approach and degrades gracefully at any terminal width.
Commas. A minority style preference places commas at the start of each new line in a SELECT column list (leading commas) rather than at the end. This makes it easier to spot a missing comma when reviewing a diff. This formatter preserves commas exactly as you place them in the input.
Popular SQL linters and formatters that influence community standards include sqlfluff (Python, highly configurable), pgFormatter (PostgreSQL-focused Perl tool), and sql-formatter (JavaScript library). Each makes slightly different choices, which is why a simple, transparent online SQL formatter with explicit controls is useful for quick formatting tasks.
When and Why to Format SQL Queries
SQL formatting is most valuable in a handful of common developer workflows. Knowing when to reach for the formatter saves time and prevents errors that stem from misreading dense query text.
Debugging production queries. Application logs, slow-query logs, and database audit logs almost always emit SQL as a single unformatted line. When a query is taking 30 seconds or returning wrong results, the first step is formatting it so you can see the full WHERE clause, JOIN conditions, and grouping logic at a glance. Pasting the log line into the SQL Formatter and copying the output takes under ten seconds and immediately reveals the query structure.
Code review. Reviewing a SQL migration or stored procedure is significantly easier when the query is formatted consistently. Many pull request review tools don't offer SQL-specific syntax highlighting or formatting, so a well-formatted query in the source file is the only formatting the reviewer will see. Teams that enforce SQL formatting in CI (via sqlfluff or similar) catch style violations before review, but a quick manual format is a low-effort habit that pays dividends.
Learning and teaching SQL. When explaining a complex query to a junior developer or writing documentation, a formatted SQL statement with proper indentation makes the logical structure of the query self-evident. The SELECT list, join chain, filter conditions, and sort order each occupy their own visual block, turning a potentially intimidating query into an approachable step-by-step description of the data transformation.
ORM output inspection. ORMs like SQLAlchemy, Hibernate, Active Record, and Sequelize generate SQL programmatically. Enabling query logging for debugging often yields extremely long, unformatted SQL strings. Running the ORM-generated query through the formatter helps you verify that the ORM is generating the query you intended and spot N+1 issues or unexpected full-table scans before they hit production.
Documentation and runbooks. SQL queries embedded in wikis, runbooks, and internal documentation benefit from consistent formatting. Future team members reading the doc will parse the query more quickly, reducing the chance of a copy-paste error when adapting the query for a slightly different use case.
Worked Examples
Simple SELECT with WHERE Clause
Problem:
Format a basic SELECT query with a WHERE filter and ORDER BY, using 2-space indent and uppercase keywords.
Solution Steps:
- 1Input: SELECT id, name, email FROM users WHERE active = 1 AND role = 'admin' ORDER BY name ASC
- 2Step 1 — Normalize whitespace: collapse to single spaces (already clean in this case).
- 3Step 2 — Insert newlines before clause keywords: SELECT, FROM, WHERE, AND, ORDER BY each go to their own line.
- 4Step 3 — Apply uppercase casing: SELECT, FROM, WHERE, AND, ORDER BY, ASC all uppercased.
- 5Step 4 — Indent continuation lines: AND starts a new line so it receives 2 leading spaces.
Result:
SELECT id, name, email FROM users WHERE active = 1 AND role = 'admin' ORDER BY name ASC
INNER JOIN with GROUP BY and HAVING
Problem:
Format a multi-table query that joins users to orders, groups by user, and filters aggregates with HAVING.
Solution Steps:
- 1Input (single line): SELECT u.id, u.name, COUNT(o.id) FROM users u INNER JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name HAVING COUNT(o.id) > 5 ORDER BY COUNT(o.id) DESC
- 2Step 1 — Normalize whitespace: already a single line, no change.
- 3Step 2 — Break on newline keywords: SELECT, FROM, INNER JOIN, ON, GROUP BY, HAVING, ORDER BY each start a new line.
- 4Step 3 — Uppercase all recognized keywords: SELECT, FROM, INNER JOIN, ON, GROUP BY, HAVING, COUNT, ORDER BY, DESC.
- 5Step 4 — Indent ON line (starts with ON) with 2 spaces.
Result:
SELECT u.id, u.name, COUNT(o.id) FROM users u INNER JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name HAVING COUNT(o.id) > 5 ORDER BY COUNT(o.id) DESC
INSERT Statement Formatting
Problem:
Format an INSERT INTO ... VALUES statement with lowercase keywords (uppercase toggle off) and 4-space indent.
Solution Steps:
- 1Input: INSERT INTO products (name, price, category_id) VALUES ('Widget', 19.99, 3)
- 2Step 1 — Normalize whitespace: single line, no change.
- 3Step 2 — Break on newline keywords: INSERT (or INTO) and VALUES each start a new line.
- 4Step 3 — Apply lowercase casing (uppercase toggle off): insert into, values all lowercased.
- 5Step 4 — No AND/OR/ON continuation lines in this query, so no indentation is applied.
Result:
insert into products (name, price, category_id) values ('Widget', 19.99, 3)
UPDATE with Multiple SET Conditions
Problem:
Format an UPDATE statement that sets multiple columns using 2-space indent and uppercase keywords.
Solution Steps:
- 1Input: UPDATE employees SET salary = 75000, updated_at = NOW() WHERE id = 42 AND department = 'engineering'
- 2Step 1 — Normalize whitespace: collapse any extra spaces.
- 3Step 2 — Break on newline keywords: UPDATE, SET, WHERE, AND each start new lines.
- 4Step 3 — Uppercase keywords: UPDATE, SET, WHERE, AND, NOW all uppercase.
- 5Step 4 — AND continuation line indented 2 spaces.
Result:
UPDATE employees SET salary = 75000, updated_at = NOW() WHERE id = 42 AND department = 'engineering'
Tips & Best Practices
- ✓Use uppercase keywords in shared codebases so SQL keywords stand out visually from column names and table aliases.
- ✓Prefer 4-space indentation for stored procedures and PL/pgSQL blocks where nested BEGIN/END structures benefit from extra visual depth.
- ✓Format SQL before pasting it into a code review comment so reviewers can focus on logic, not layout.
- ✓After formatting a slow query from a log, scan the WHERE clause first — AND/OR indentation reveals whether conditions are grouped the way you intended.
- ✓Run ORM-generated queries through the formatter during debugging to verify the ORM is applying the correct joins and filters.
- ✓Keep your SQL formatter settings consistent with your team's linter config (sqlfluff, sql-fluff, or similar) to avoid constant reformatting churn.
- ✓Use lowercase keywords when embedding SQL in YAML config files or JSON payloads where UPPERCASE can look visually aggressive.
- ✓Format SQL examples in documentation and runbooks so new team members can parse query structure at a glance without needing deep SQL expertise.
Frequently Asked Questions
Sources & References
Last updated: 2026-06-05
Help us improve!
How would you rate the SQL Formatter?
Editorial Note
MyCalcBuddy Editorial Team
This page is maintained as an educational calculator reference.
Formula Source: Standard Mathematical References
by Various