HomeToolsFormattingSQL Formatter

SQL Formatter

Format, beautify, and clean up your SQL queries with customizable casing and indentation.

Formatting
Keyword Case:
Indent:
Input SQL
Formatted SQL

Use formatting to reveal the shape of a query

SQL becomes difficult to reason about when joins, predicates, grouping, and nested selects occupy one visual stream. The SQL Formatter separates major clauses, applies a keyword case preference, spaces selected operators, and optionally places AND and OR conditions on new lines. Two-space, four-space, and tab indentation are available, and output can be copied or downloaded as query.sql.

The formatter tokenizes common keywords, identifiers, quoted strings, numbers, comments, symbols, and whitespace. It merges selected two-word clauses such as GROUP BY, ORDER BY, LEFT JOIN, INSERT INTO, and CREATE TABLE, then prints recognized major clauses on fresh lines. This gives ordinary queries useful structure without connecting to a database.

Follow one query through the controls

Input:

select u.id,u.email,count(o.id) as orders from users u left join orders o on o.user_id=u.id where u.active=1 and o.created_at>='2026-01-01' group by u.id,u.email having count(o.id)>2 order by orders desc;

With uppercase keywords, two spaces, and newline conditions enabled, output is arranged approximately as:

SELECT u.id, u.email, count(o.id) AS orders
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.active = 1
  AND o.created_at > = '2026-01-01'
GROUP BY u.id, u.email
HAVING count(o.id) > 2
ORDER BY orders DESC;

The separated > = illustrates an implementation limit: operators are tokenized one symbol at a time, so multi-character operators may not remain conventionally joined. Always review comparisons such as >=, <=, <>, !=, PostgreSQL casts and JSON operators, and dialect-specific symbols before executing output.

Keyword case and indentation

Keyword Case offers uppercase, lowercase, capitalized, or preserved spelling. Only recognized keywords change. Identifiers and quoted text retain their case. Uppercase keywords are a common way to distinguish grammar from schema names; lowercase fits projects where generated SQL and application code use that convention. Preserve minimizes cosmetic changes to existing source.

Indent determines nested subquery indentation and the extra level used for newline conditions. Tabs may align differently across clients, while spaces produce stable visual widths. Match repository conventions and avoid reformatting unrelated statements merely to impose a preference.

Newline on AND/OR places recognized logical connectors on a new line with one additional indent level. Disabling it leaves them inline with spaces. This option improves long WHERE and HAVING clauses, but it does not understand Boolean precedence or add parentheses. AND binds more tightly than OR in common dialects, so layout must never be interpreted as a semantic grouping guarantee.

Comments beginning with --, #, and block comments are recognized and moved to an indented line. Hash comments are dialect-specific. Strings delimited by single quotes, double quotes, or backticks are kept as string tokens, although the meaning of those delimiters varies by database and SQL mode.

A query-review workflow

Paste a single statement or a small related batch. Select Preserve first to reduce changes, then choose project casing and indentation. Toggle condition newlines while checking the exact predicate order. Compare strings, quoted identifiers, placeholders, comments, operators, and terminators.

Copy the result into a SQL-aware client connected to a safe environment, or download it for review. Parse or prepare the statement using the target database version and driver. Use representative bind parameters rather than substituting user input into query text.

For a SELECT, inspect the execution plan and test returned rows, ordering, null behavior, collation, time zones, and boundary values. For INSERT, UPDATE, DELETE, DDL, or administrative SQL, use a transaction where the database supports the intended rollback, verify backups, and obtain appropriate review. Formatting does not lower the operational risk of a write statement.

Keep migrations under the project’s migration framework. Some migration runners split statements using their own delimiter rules or store checksums of exact file contents; cosmetic edits to an applied migration can trigger validation failures. Format before release, not after application.

Dialects are not interchangeable

SQL is a family of languages. PostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle, BigQuery, Snowflake, and others differ in quoting, operators, functions, procedural blocks, limit syntax, upserts, returning clauses, and DDL. This formatter has no dialect selector despite handling broadly familiar clauses.

PostgreSQL dollar-quoted strings, casts such as ::, array operators, JSON operators, and DISTINCT ON require special handling. MySQL modes affect double quotes and backslash escapes. SQL Server bracketed identifiers, GO batch separators, and TOP have distinct grammar. Oracle procedural code and slash terminators introduce another layer. Treat unfamiliar dialect syntax as a reason to use the database-specific formatter.

The keyword set is finite. Unrecognized keywords remain identifiers and may not receive casing or clause line breaks. DELETE FROM is merged internally but is not listed among the major printed clauses in the same way as several others, and procedural statements receive no block indentation.

Strings handle backslash escapes in the tokenizer, but SQL-standard escaping often doubles quote characters. Dialect mode determines whether backslashes are special. A browser formatter cannot infer session settings such as standard_conforming_strings, ANSI_QUOTES, or quoted identifier behavior.

Formatting cannot make dynamic SQL safe

Readable SQL is still vulnerable if an application concatenates untrusted values into it. Parameterized queries or prepared statements keep data separate from SQL grammar. Parameters should also be used for dates, numbers, and Boolean values, not only obvious text fields.

Identifiers such as table names and sort directions usually cannot be bound as ordinary values. Choose them from a strict allowlist rather than copying user text. Least-privilege database roles, statement timeouts, transaction boundaries, and audit logging remain essential.

Do not paste production credentials or sensitive customer literals into a formatting page. Redact values and preserve parameter placeholders. The component does not establish a database connection, but local policy and browser extensions may still govern handling of confidential material.

Formatting also does not optimize a query. Clause layout can help humans notice a missing join predicate or non-sargable expression, but the query planner decides access paths using schema, statistics, indexes, parameters, and configuration. Use EXPLAIN or the database’s plan tooling in an appropriate environment.

Check token boundaries after formatting

The preview is especially useful as a token-level diff aid. Compare every punctuation-heavy expression with the input, not just the clause layout. The component recognizes decimal text by consuming digits and periods together, recognizes identifiers from letters, digits, and underscores, and treats every remaining character as an individual symbol. Schema-qualified names, named parameters, dollar parameters, bracketed identifiers, and escaped quotes may therefore need closer inspection than ordinary words. If a statement relies on those forms, copy the result into a dialect-aware editor and verify the parser accepts the exact formatted text before replacing the source.

Diagnose output before diagnosing the database

A compound operator gained a space. Restore the operator and switch to a dialect-aware parser formatter for statements containing >=, !=, ::, ->>, or similar syntax.

A keyword did not change case. It may not be in the formatter’s recognized keyword set. That does not imply invalid SQL.

A subquery indents strangely. Parentheses followed by a recognized SELECT trigger subquery indentation. Parentheses used for expressions or functions follow simpler handling, and nested dialect constructs may confuse the level.

A comment moved away from its target. Comments are printed on their own line. Verify optimizer hints, migration directives, and comments documenting a specific expression.

Formatted SQL returns different rows. Stop and compare exact tokens, especially operators, strings, comments, and Boolean expressions. Run neither version against production writes until the difference is understood.

SQL Formatter FAQ

Does the tool execute SQL?

No. It only transforms text. There is no database connection, schema lookup, result grid, or transaction.

Which SQL dialect does it support?

It recognizes a practical set of common clauses, but no single dialect is selected or fully implemented. Validate against the actual database.

Does it preserve quoted values?

Quoted tokens are intended to remain intact, but escaping rules differ by dialect. Inspect strings and quoted identifiers carefully.

Can it prevent SQL injection?

No. Use driver-supported parameters, identifier allowlists, and least-privilege credentials. Formatting is unrelated to trust boundaries.

Why put AND and OR on separate lines?

It makes long predicates easier to scan and edit. It does not change or communicate precedence reliably; explicit parentheses are required when grouping must be unmistakable.

Is formatted SQL faster?

Whitespace and keyword case generally do not improve execution. Analyze plans, indexes, statistics, cardinality, locking, and data access patterns.

What should I verify before using downloaded SQL?

Run the canonical dialect formatter and parser, inspect the diff, prepare with safe parameters, test in a non-production database, review the plan and result set, and apply normal controls for writes or migrations.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →