SQL Formatter & Beautifier
Format, beautify and minify SQL queries instantly
Output updates as you type
π Runs entirely in your browser β your SQL is never sent to a server or stored anywhere.
Why SQL Formatting Matters
A SQL query that works is not necessarily a SQL query that communicates. Raw, unformatted SQL β especially the kind copied from an ORM's debug output or a log file β collapses joins, conditions, and aggregations into a single dense wall of text that is nearly impossible to audit quickly. Compare these two queries that do the same thing:
-- Unformatted: select u.id,u.name,o.total from users u inner join orders o on u.id=o.user_id where o.status='completed' and o.total>100 order by o.created_at desc limit 20 -- Formatted: SELECT u.id, u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.status = 'completed' AND o.total > 100 ORDER BY o.created_at DESC LIMIT 20
The formatted version makes the query's intent immediately obvious: you can read the selected columns, understand the join relationship, and check each WHERE condition as a distinct logical step. In a code review, formatted SQL lets reviewers verify business logic in seconds rather than minutes.
Consistent formatting also makes version control diffs meaningful. When SQL is always formatted the same way, a commit that changes a single WHERE condition shows exactly one line changed β not a scrambled diff of whitespace changes mixed with logical changes.
Writing Readable SQL: Core Formatting Principles
The SQL community has converged on a small set of formatting principles that virtually all modern style guides agree on. Understanding these principles helps you decide when to apply them and why.
1. One clause per line
Major SQL clauses β SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, HAVING, LIMIT β each belong on their own line. This creates a natural left margin of clause keywords that acts as a table of contents for the query. A developer skimming the query can instantly see which clauses are present and jump directly to the one they need to examine.
2. Indent continuation lines
Items within a clause should be indented: column names after SELECT, filter conditions joined by AND or OR after WHERE. This indentation signals that these items are subordinate to the clause keyword above them. Two-space indentation is the most common choice; four spaces also works well.
3. Uppercase SQL keywords
Capitalizing reserved words (SELECT, FROM, WHERE, AND, CASE, etc.) while writing table and column names in lowercase is the dominant SQL convention for a good reason: it makes the structural skeleton of the query visible at a glance. The SELECTβFROMβWHERE pattern stands out from user-defined identifiers. GitLab's SQL style guide, the Mozilla SQL style guide, and most enterprise SQL linting tools all recommend uppercase keywords.
4. Spaces around operators
Comparison and arithmetic operators should have a space on each side: total > 100 rather than total>100. This is one of the most visually impactful formatting choices because it prevents conditions from blurring together, especially when multiple conditions appear in a single line.
Common SQL Formatting Mistakes (and How to Avoid Them)
Even developers who care about SQL formatting often make a few recurring mistakes. Here are the most common, along with the correct approach.
Putting AND/OR at the end of a line
Some style guides put AND at the end of the preceding line; others put it at the start of the next. The leading-AND style (shown in this formatter's output) is generally preferred because it makes it easy to comment out a single condition without breaking the query β you can comment the entireAND condition line and the query still parses correctly. Trailing-AND style requires editing two lines (removing AND from the preceding line) to safely disable a condition.
Writing deep subqueries inline
A WHERE clause that contains a nested subquery that itself contains another subquery becomes unreadable faster than almost anything else in SQL. The correct solution is not to format the nesting more carefully β it is to extract each subquery into a named CTE:
-- Hard to read (deep inline subquery):
SELECT * FROM products WHERE id IN (
SELECT product_id FROM order_items WHERE order_id IN (
SELECT id FROM orders WHERE user_id = 42 AND status = 'completed'
)
)
-- Much clearer with CTEs:
WITH user_orders AS (
SELECT id FROM orders WHERE user_id = 42 AND status = 'completed'
),
purchased_products AS (
SELECT product_id FROM order_items WHERE order_id IN (SELECT id FROM user_orders)
)
SELECT * FROM products WHERE id IN (SELECT product_id FROM purchased_products)Named CTEs serve as documentation β each intermediate result set has a name that describes its meaning, which makes the overall query self-documenting.
Inconsistent alias casing
If you alias a table as u in one query and U in another, SQL will handle it (most databases are case-insensitive for identifiers), but your teammates will have to do a mental mapping every time they read the query. Pick a consistent casing convention for aliases β typically lowercase single letters or short abbreviations β and stick to it across your codebase.
SQL Formatting in Team Environments
Individual developers formatting SQL consistently is good. A whole team doing it the same way automatically is much better. There are several tools that enforce SQL formatting at various points in the development workflow.
SQLFluff
SQLFluff is an open-source SQL linter and formatter that supports MySQL, PostgreSQL, BigQuery, Snowflake, Spark, dbt, and a dozen other dialects. It can be run as a pre-commit hook, in CI/CD pipelines, or integrated into editors. SQLFluff's configuration file lets teams define their exact style rules (indentation width, keyword case, comma placement) and enforce them automatically.
dbt's SQL formatting conventions
The dbt community has developed widely adopted SQL conventions, including the practice of using CTEs for all intermediate result sets, writing column lists with leading commas (so adding a column only requires adding one line), and defining all column aliases with the AS keyword. These conventions are opinionated but dramatically improve readability in data warehousing workloads where a single model may contain hundreds of lines of SQL.
When to format automatically vs. manually
Automated formatters work best for regular DML queries. For SQL embedded inside application code (Python, Java, TypeScript), automatic formatting of multi-line string literals is trickier and often requires format-on-save editor plugins. For ad-hoc queries run in a SQL IDE like DBeaver, TablePlus, or DataGrip, those tools have built-in formatters accessible with a keyboard shortcut. This online formatter is most useful for one-off queries, for formatting SQL you receive from others, or for cleaning up queries copied from log output.
Advanced SQL Patterns and How They Format
Modern SQL has grown far beyond the basic SELECTβFROMβWHERE trifecta. Here is how this formatter handles more advanced constructs.
Window functions
Window functions (OVER, PARTITION BY, ORDER BY within OVER) are handled as part of the SELECT clause. The PARTITION BY and ORDER BY inside an OVER clause are treated as part of the inline expression rather than top-level clauses, so they stay on the same line as the function call. For very long window function expressions, you can break them manually into CTEs for clarity.
CASE expressions
CASE β¦ WHEN β¦ THEN β¦ ELSE β¦ END expressions are common for conditional logic in SQL. When a CASE expression is short, keeping it on one line is fine. When it has multiple WHEN branches, formatting each WHEN on its own line with consistent indentation makes the branching logic much clearer β the same way if-else branches are formatted in general programming languages.
Multiple statements
This formatter handles multiple SQL statements separated by semicolons. Each statement is formatted independently, so you can paste a migration script containing CREATE TABLE, ALTER TABLE, and INSERT statements and get all of them formatted in a single pass. Each formatted statement is separated by a blank line for readability.
Frequently Asked Questions
What is SQL formatting and why does it matter?
SQL formatting (also called SQL beautification or pretty-printing) transforms minified or inconsistently spaced SQL queries into a consistently indented, readable structure. Well-formatted SQL separates major clauses like SELECT, FROM, WHERE, and JOIN onto their own lines, aligns list items after commas, and indents continuation conditions such as AND and OR. Readable SQL reduces the time spent understanding a query by an order of magnitude β especially for complex queries with multiple JOINs or nested subqueries. In team environments, consistent formatting prevents style drift where different developers format their queries differently, making code reviews harder and version diffs noisier.
Which SQL dialects does this formatter support?
This tool formats standard SQL syntax that works across the most common relational databases, including MySQL, PostgreSQL, SQLite, SQL Server (T-SQL), and Oracle. It correctly handles SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, and DROP statements, as well as JOINs, GROUP BY, ORDER BY, HAVING, LIMIT, OFFSET, UNION, CTEs (WITH clauses), subqueries, CASE expressions, and window functions. Because SQL keyword formatting is dialect-independent β the rules are the same whether you are writing PostgreSQL or MySQL β the formatter works reliably across all major databases.
Does this tool store or log my SQL queries?
No. This SQL formatter runs entirely in your browser using JavaScript β your SQL is never sent to a server, logged, or stored anywhere. This makes it safe to use with sensitive queries that reference production table names, column names, or contain hardcoded filter values. You can format confidential database schemas or internal business queries without any privacy risk.
What does the "Uppercase Keywords" option do?
The uppercase keywords option converts all SQL reserved words β SELECT, FROM, WHERE, AND, OR, JOIN, GROUP BY, ORDER BY, and so on β to UPPER CASE. This is the most widely used SQL convention, recommended by most SQL style guides including the SQL Style Guide and GitLab's SQL guidelines, because it visually distinguishes SQL keywords from table names, column names, and aliases. If your team prefers lowercase keywords (a valid minority style), you can turn this option off to keep the original keyword casing from your input.
Can I use this SQL formatter for stored procedures and CTEs?
Yes. This tool handles CTEs (Common Table Expressions) with the WITH keyword, CASE ... WHEN ... THEN ... ELSE ... END expressions, and multi-statement SQL separated by semicolons. For stored procedures with procedural extensions (such as PostgreSQL's PL/pgSQL, SQL Server's T-SQL BEGIN...END blocks, or MySQL's DELIMITER syntax), the formatter correctly handles the SQL portions inside the procedure but may not format dialect-specific procedural constructs. For pure SQL queries β which make up the vast majority of formatting needs β the tool works fully and accurately.
How should I format SQL subqueries and nested queries?
Subqueries inside parentheses are handled by this formatter: each opening parenthesis increases the nesting level, and the content inside is formatted as a continuous block. For very deep nesting, you may want to break out subqueries into CTEs (WITH clauses) instead, since CTEs give each subquery a name that makes the overall logic clearer β and they format much more readably than inline subqueries four levels deep. A good rule of thumb is to extract any subquery you would reference more than once, or any subquery over three lines, into a named CTE.
What is SQL minification and when would I use it?
SQL minification removes all unnecessary whitespace and newlines, collapsing a multi-line formatted query into the most compact single-line form. You would minify SQL when embedding queries in configuration files, environment variables, or log messages where whitespace adds no value and line breaks cause parsing issues. Minification also helps when comparing two queries programmatically β normalized, whitespace-stripped SQL is easier to hash or diff. Note that most database query parsers handle both formatted and minified SQL identically, since SQL is not whitespace-sensitive.