SQL Formatter
Format and prettify messy SQL queries with proper indentation, keyword casing, and line breaks. Runs entirely in your browser.
This SQL formatter takes messy, single-line, or poorly indented SQL queries and reformats them with proper indentation, line breaks at clause boundaries, and consistent keyword casing. Paste your query, choose your formatting preferences, and get clean, readable SQL. Everything runs in your browser - your queries never leave your machine.
About SQL Formatter
What Does the Formatter Do?
The formatter identifies SQL keywords and structures the query with each major clause on its own line:
| Keyword/Clause | Formatting Rule |
|---|---|
| SELECT, FROM, WHERE, JOIN, ORDER BY, GROUP BY, HAVING, LIMIT | New line, no indentation (top-level clauses) |
| AND, OR | New line, indented under WHERE/HAVING |
| ON | Indented under JOIN |
| Column lists after SELECT | Each column on its own line, indented |
| String literals | Preserved exactly as written |
| Subqueries | Indented inside parentheses |
Before:
select u.id, u.name, o.total from users u inner join orders o on u.id = o.user_id where o.total > 100 and u.active = 1 order by o.total desc limit 10;
After (uppercase keywords, 2-space indent):
SELECT
u.id,
u.name,
o.total
FROM users u
INNER JOIN orders o
ON u.id = o.user_id
WHERE
o.total > 100
AND u.active = 1
ORDER BY o.total DESC
LIMIT 10;
How SQL Formatting Works
The formatter parses your input by first extracting and protecting string literals (anything inside single quotes), then collapsing all whitespace into single spaces. It then scans for SQL keywords using a longest-match-first approach so that multi-word keywords like LEFT OUTER JOIN are matched before shorter ones like LEFT or JOIN. Each major clause keyword triggers a new line, while sub-clause keywords like AND, OR, and ON get indented beneath their parent clause. Parentheses are tracked for subquery depth, and the indentation level increases inside each nested subquery.
Worked example with a subquery:
Input: select name, (select count(*) from orders where orders.user_id = users.id) as order_count from users where active = 1
Output:
SELECT
name,
(
SELECT COUNT(*)
FROM orders
WHERE orders.user_id = users.id
) AS order_count
FROM users
WHERE active = 1
The formatter preserves all table names, column names, string values, and operators exactly as written. Only whitespace and keyword casing change - the formatted query is functionally identical to the original.
Formatting Options
| Option | Choices | Convention |
|---|---|---|
| Indentation | 2 spaces or 4 spaces | 2 spaces is more common in SQL |
| Keyword casing | UPPERCASE or lowercase | Uppercase is the dominant convention for readability |
The keyword casing debate has been running for decades. The traditional convention is uppercase keywords (SELECT, WHERE, JOIN) because it visually separates SQL structure from table and column names. Simon Holywell's widely referenced SQL style guide at sqlstyle.guide recommends uppercase reserved keywords, and this remains the most common convention in production codebases. The modern counter-argument, made in guides like Matt Mazur's GitHub SQL style guide, is that lowercase keywords are easier to type and that syntax highlighting in modern editors makes casing less important. Both approaches are valid - the key is consistency within a project.
Why Format SQL?
SQL remains one of the most widely used languages in software development. In the 2025 Stack Overflow Developer Survey, SQL ranked among the top five most-used languages alongside JavaScript, Python, TypeScript, and Java. PostgreSQL is now the most-used database among professional developers at 55.6%, followed by MySQL, SQL Server, and SQLite. With that volume of SQL being written daily, formatting matters.
| Reason | Detail |
|---|---|
| Readability | Formatted queries are much easier to scan and understand, especially complex JOINs |
| Debugging | Clause-per-line formatting makes it easier to comment out sections while testing |
| Code review | Consistent formatting makes diffs cleaner and reviews faster |
| Documentation | Well-formatted SQL in docs and wikis is easier to follow |
| Team consistency | A formatter eliminates style arguments |
| Error spotting | Misplaced clauses and missing conditions are obvious when each clause sits on its own line |
LearnSQL's "24 Rules to the SQL Formatting Standard" highlights that ignoring formatting conventions causes real problems in team environments. When everyone writes SQL differently, reviewing pull requests becomes slower, merging branches creates unnecessary conflicts, and onboarding new team members takes longer.
SQL Keyword Reference
The formatter recognises all major SQL keywords across common dialects:
| Category | Keywords |
|---|---|
| Data Query (DQL) | SELECT, FROM, WHERE, JOIN, ON, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, UNION, INTERSECT, EXCEPT, DISTINCT, AS |
| Data Manipulation (DML) | INSERT INTO, VALUES, UPDATE, SET, DELETE FROM, MERGE |
| Data Definition (DDL) | CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, CREATE VIEW |
| Logical operators | AND, OR, NOT, IN, BETWEEN, LIKE, IS NULL, IS NOT NULL, EXISTS |
| Join types | INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN |
| Aggregate functions | COUNT, SUM, AVG, MIN, MAX |
| Window functions | OVER, PARTITION BY, ROW_NUMBER, RANK, DENSE_RANK |
| CTEs | WITH, RECURSIVE |
| Subquery | Recognised by parentheses - indented automatically |
Dialect Compatibility
| Database | Compatible? | Notes |
|---|---|---|
| PostgreSQL | Yes | Standard SQL with PG extensions. Most popular DB among devs as of 2025. |
| MySQL / MariaDB | Yes | Backtick identifiers preserved |
| SQLite | Yes | Standard SQL subset |
| SQL Server (T-SQL) | Yes | TOP, bracket identifiers preserved |
| Oracle | Yes | Standard SQL with Oracle extensions |
| BigQuery | Yes | Standard SQL mode |
The formatter works with standard SQL syntax that is common across all these dialects. Dialect-specific extensions (like PostgreSQL's JSONB operators or MySQL's backtick quoting) are preserved as-is.
SQL Style Best Practices
Several widely adopted style guides agree on a core set of SQL formatting rules. The GitLab Data Team SQL Style Guide, Simon Holywell's sqlstyle.guide, and Mozilla's SQL Style Guide all share similar principles:
| Practice | Why |
|---|---|
| One column per line in SELECT | Makes diffs cleaner and columns easier to add/remove |
| Uppercase keywords | Visually separates SQL structure from table/column names |
| Alias tables consistently | Short aliases (u, o) make complex queries more readable |
| Put each JOIN on its own line | Makes the table relationships visible at a glance |
| Indent sub-clauses | Shows the logical hierarchy of the query |
| Use CTEs over deeply nested subqueries | Named intermediate steps are easier to read and debug than nested parentheses |
| Avoid SELECT * | Explicit column lists make intent clear and prevent unexpected columns from appearing |
| Use snake_case for identifiers | Most style guides prefer employee_city over EmployeeCity or employeecity |
Common SQL Formatting Mistakes
A few patterns consistently make SQL harder to read:
- Everything on one line. A 200-character single-line query with multiple JOINs and WHERE conditions is almost impossible to debug. Each clause should start on its own line.
- Inconsistent casing. Mixing SELECT with select and Select in the same file makes the code look unfinished. Pick one convention and stick with it.
- No indentation on sub-clauses. When AND conditions sit at the same indentation level as FROM and WHERE, the query's logical structure is hidden. Indent conditions under their parent clause.
- Cramming subqueries inline. A subquery in a WHERE clause should be on its own indented block, not jammed into the middle of a line.
- Trailing commas vs leading commas. Both work, but trailing commas (column1, column2,) are more common and match most auto-formatters. The important thing is picking one style per project.
How Does Formatting Interact With CTEs and Window Functions?
Common Table Expressions (CTEs) introduced with the WITH keyword are one of the biggest improvements to SQL readability. Instead of nesting subqueries three or four levels deep, CTEs let you name each logical step. A well-formatted CTE-based query reads almost like a recipe: first do this, then do that, finally combine the results.
CTE formatting example:
WITH
active_users AS (
SELECT id, name, email
FROM users
WHERE active = 1
),
recent_orders AS (
SELECT user_id, SUM(total) AS total_spent
FROM orders
WHERE created_at >= '2024-01-01'
GROUP BY user_id
)
SELECT
u.name,
u.email,
o.total_spent
FROM active_users u
INNER JOIN recent_orders o
ON u.id = o.user_id
ORDER BY o.total_spent DESC
Window functions follow a similar pattern. The OVER clause and its PARTITION BY and ORDER BY sub-clauses should be kept together, with indentation showing the window definition clearly. Queries that rank rows, calculate running totals, or compute moving averages all benefit from consistent formatting because the window specification is often the most complex part of the query.
Formatting INSERT, UPDATE, and DELETE Statements
Most formatting discussions focus on SELECT queries, but DML statements benefit just as much from consistent formatting. A multi-row INSERT with dozens of value sets is much easier to verify when each row sits on its own line. UPDATE statements with multiple SET assignments are clearer when each assignment gets its own line. DELETE statements with complex WHERE conditions follow the same rules as SELECT - one condition per line, indented under the WHERE clause.
INSERT formatting example:
INSERT INTO orders (user_id, product_id, quantity, total)
VALUES
(1, 42, 2, 59.98),
(1, 17, 1, 24.99),
(3, 42, 5, 149.95);
UPDATE formatting example:
UPDATE users
SET
last_login = NOW(),
login_count = login_count + 1,
status = 'active'
WHERE id = 42;
This formatter handles all three DML statement types, placing each clause keyword on its own line and indenting sub-clauses consistently.
Automating SQL Formatting in a Team Workflow
For individual queries, pasting into an online formatter like this one is the quickest option. For teams that want consistent formatting across every commit, most CI/CD pipelines can run a SQL linter as a pre-commit hook or build step. Tools like sqlfluff (Python-based) and pgFormatter (Perl-based) can be integrated into GitHub Actions or GitLab CI. The principle is the same as running Prettier on JavaScript or Black on Python - format on save, format on commit, and never argue about style in code review again.
Whichever approach a team picks, the core rules stay the same: one clause per line, consistent keyword casing, indented sub-clauses, and explicit column lists. This formatter applies those rules instantly, giving you a clean starting point that any style guide would approve of.
For formatting other languages, the JSON Formatter handles JSON data, the HTML Prettifier formats markup, and the JavaScript Formatter prettifies JS code. If you need to validate patterns in your SQL strings, the Regex Tester can help test extraction patterns.
All processing happens in your browser. Your SQL is never sent to any server.
Sources
Frequently Asked Questions
What does the SQL formatter do?
It takes messy or single-line SQL queries and reformats them with proper indentation, line breaks before major clauses like SELECT, FROM, WHERE, and JOIN, and consistent keyword casing. The output is much easier to read and debug.
Does it uppercase SQL keywords automatically?
Yes, by default the formatter converts all SQL keywords to uppercase which is the most common convention. You can toggle this off if you prefer lowercase keywords instead.
Will the formatter change how my query runs?
No. The formatter only changes whitespace and letter casing on keywords. It does not modify the logic, table names, column names, or string values in your query. The formatted output is functionally identical to the original.
Is my SQL sent to a server?
No. All formatting happens in your browser using JavaScript. Your queries are never transmitted anywhere, making this safe for proprietary or sensitive SQL.
What SQL dialects does it support?
The formatter works with standard SQL syntax that is common across PostgreSQL, MySQL, SQLite, SQL Server, and Oracle. It recognises all major keywords and clause structures used in these dialects.
Related Tools
Link to this tool
Copy this HTML to link to this tool from your website or blog.
<a href="https://toolboxkit.io/tools/sql-formatter/" title="SQL Formatter - Free Online Tool">Try SQL Formatter on ToolboxKit.io</a>