The short answer: select the dialect that will execute the query, then format with rules that recognize that dialect's tokens and grammar. A generic formatter may misread backticks, brackets, dollar-quoted strings, executable comments, QUALIFY, TOP, or vendor-specific operators. Formatting improves presentation; it does not prove that a statement is syntactically valid, that names and types exist, that permissions allow it, that it is safe, or that it returns the intended result. Validation and execution are separate steps.
Why SQL dialects change formatting
SQL is standardized, but production databases implement families of related languages rather than one interchangeable grammar. A basic SELECT, FROM, WHERE, and ORDER BY sequence travels well. The edges do not. Each engine adds data types, functions, operators, procedural statements, query clauses, identifier rules, comments, and client commands. Some use the same punctuation for different purposes.
A formatter must first recognize tokens: which characters start a string, identifier, parameter, comment, operator, or statement boundary. It then needs enough structural knowledge to indent clauses and expressions without moving text across a meaningful boundary. Choosing the wrong dialect can therefore do more than produce an unfashionable style. It can split one token into several, treat executable text as a comment, change where a statement appears to end, or place a vendor clause in the wrong part of a query.
| Feature | MySQL | PostgreSQL | BigQuery GoogleSQL | SQL Server T-SQL |
|---|---|---|---|---|
| Common quoted identifier | Backticks | Double quotes | Backticks | Brackets; double quotes with the relevant setting |
| Common row limit | LIMIT | LIMIT | LIMIT | TOP or OFFSET … FETCH |
| Notable literal form | SQL-mode-dependent string behavior | Dollar-quoted strings | Raw and triple-quoted strings | Unicode strings prefixed with N |
| Notable extension | Executable version comments | :: casts and rich operators | ARRAY, STRUCT, UNNEST, QUALIFY | Variables, temporary objects, table hints, batches |
These are useful recognition clues, not a reliable dialect detector. Backticks occur in both MySQL and BigQuery. Double-quoted identifiers occur in standard SQL and PostgreSQL and can occur in SQL Server. A query may also be valid in multiple engines. The authoritative answer is the destination database and version, plus any compatibility or SQL-mode settings used there.
Formatting is not validation or execution
A SQL formatter rearranges presentation. Typical operations include adding line breaks, selecting an indentation width, changing the case of recognized keywords, and aligning or separating clauses. A well-designed formatter preserves string contents, identifiers, comments, parameter markers, and operator meaning. Some formatters build a syntax tree; others use a tolerant tokenizer and layout rules so they can still format incomplete work.
That behavior is valuable, but it does not establish correctness. A formatter can produce attractive output from a misspelled column, an inaccessible table, incompatible types, a function absent from the target version, or a query with the wrong join condition. Even a parser-backed formatter usually knows only the grammar it implements. It does not necessarily have the live database catalog, session settings, user privileges, temporary objects, stored routines, or parameter types.
Never use “formatted successfully” as an approval signal. Formatting is not syntax validation, schema validation, query planning, execution, security review, or a test of business intent. Validate with tooling for the exact engine and version, inspect the diff, and execute only in an appropriately isolated environment with the intended parameters and permissions.
The reverse is also important: a formatter error does not prove that the database will reject the statement. The formatter may lag a new engine feature, encounter a template directive, or support only a subset of stored-program syntax. Preserve the original query and report the formatting limitation instead of “repairing” unfamiliar text automatically.
Style choices that can be shared safely
Teams can standardize many visual choices across dialects. Uppercase or lowercase keywords, two or four spaces, blank lines between common table expressions, and a target expression width are presentation policies. Some formatters also expose leading- or trailing-comma controls; LiveParse currently follows its formatting engine's comma layout and does not expose a comma-style setting. Consistency reduces review noise and makes joins, filters, grouping, window definitions, and nested subqueries easier to scan.
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spend
FROM orders
WHERE created_at >= :start_time
GROUP BY customer_id
HAVING COUNT(*) > 1
ORDER BY total_spend DESC;
Even this example is not completely portable. The named parameter :start_time is a client convention rather than universal server syntax. A PostgreSQL driver might use $1; BigQuery supports named parameters such as @start_time and positional question marks; SQL Server variables commonly begin with @; another client may substitute values before the database sees the query. Formatting configuration must distinguish placeholders from operators and casts.
Keyword case changes are normally safe only for tokens confidently recognized as keywords. Never case-fold quoted identifiers, string literals, JSON paths, regular expressions, aliases, or template expressions. Do not reorder predicates, columns, joins, or common table expressions merely to “normalize” them. Reordering can change evaluation, duplicate-name resolution, volatile function calls, lock behavior, output column order, or simply the intended review history.
Formatting MySQL
MySQL commonly quotes identifiers with backticks. Double quotes normally delimit strings, but ANSI_QUOTES changes their role to quoted identifiers. Other SQL modes affect escaping and parsing. A formatter that guesses from punctuation without knowing the configured mode can misclassify text. Preserve the original quote characters unless a separate, deliberate migration is underway.
Comments deserve special care. MySQL supports # line comments, block comments, and a double-dash form whose second dash must be followed by whitespace or a control character. It also supports executable comments such as /*! ... */, version-qualified executable comments, and optimizer hints beginning with /*+. These blocks may look decorative to a generic SQL formatter, but the server can act on their contents. They must remain attached to the intended statement and must not be discarded.
SELECT /*+ BKA(o) */
o.`order`,
JSON_UNQUOTE(JSON_EXTRACT(o.payload, '$.customer.id')) AS customer_id
FROM `sales`.`orders` AS o
WHERE o.created_at >= ?
ORDER BY o.created_at DESC
LIMIT 25 OFFSET 50;
The formatter can separate the clauses and indent the expressions. It should not convert backticks to double quotes, reinterpret the JSON path, move the hint away from the statement it guides, or replace LIMIT with another engine's syntax. For focused work, use the MySQL SQL Formatter. Oracle's official MySQL 8.4 Language Structure documents literals, identifiers, keywords, expressions, and comments; formatting policy should start from those lexical rules.
Formatting PostgreSQL
PostgreSQL folds unquoted identifiers to lowercase, while double-quoted identifiers preserve spelling and case. A formatter may uppercase keywords, but it must not change identifier quoting or case. PostgreSQL also supports dollar-quoted strings, including tagged delimiters such as $function$ ... $function$. Their contents can contain quotes, semicolons, comments, and procedural code without ending the outer string.
Operators are another boundary. PostgreSQL uses :: casts and has operator families for arrays, ranges, full-text search, JSON, and extensions. The tokens ->, ->>, #>, @>, and others are not arbitrary punctuation to space or split character by character. Nested block comments are supported, so a tokenizer designed around the first closing marker can also end a comment too early.
WITH recent_orders AS (
SELECT
id,
payload ->> 'customer_id' AS customer_id,
created_at::date AS order_date
FROM sales.orders
WHERE created_at >= $1::timestamptz
)
SELECT customer_id, COUNT(*) AS order_count
FROM recent_orders
GROUP BY customer_id
ORDER BY order_count DESC
LIMIT 25 OFFSET 50;
Stored functions raise the stakes because a dollar-quoted body may contain PL/pgSQL or even another language. Format the outer SQL and embedded language only when the tool explicitly understands both layers. Otherwise preserve the body as an opaque literal. The PostgreSQL SQL Formatter selects PostgreSQL-aware layout, while the official PostgreSQL lexical structure is the primary reference for tokens, quoted identifiers, constants, dollar quoting, comments, and operators.
Formatting BigQuery GoogleSQL
BigQuery's GoogleSQL dialect uses backticks for quoted identifiers, including fully qualified paths such as `project.dataset.table`. That looks superficially like MySQL, but BigQuery's grammar includes nested and repeated data, ARRAY and STRUCT constructors, UNNEST, QUALIFY, wildcard tables, and cloud-specific statements. Selecting MySQL because a query contains backticks will misclassify many of these structures.
GoogleSQL string and bytes literals have several prefixes and quoting forms, including raw and triple-quoted literals. Literal chunks can be concatenated under documented separation rules. A formatter must scan the full literal form before interpreting commas, comment markers, backslashes, or newlines within it. Query parameters may be named with @name or positional with ?, but they cannot replace identifiers.
SELECT
o.order_id,
item.sku,
item.quantity,
SUM(item.quantity) OVER (
PARTITION BY o.customer_id
) AS customer_units
FROM `analytics-prod.sales.orders` AS o
CROSS JOIN UNNEST(o.items) AS item
WHERE o.created_at >= @start_time
QUALIFY ROW_NUMBER() OVER (
PARTITION BY o.customer_id
ORDER BY o.created_at DESC
) <= 25;
A helpful layout makes nested expressions and window specifications visible without flattening a backtick path or detaching QUALIFY from the query block it filters. Use the BigQuery SQL Formatter for GoogleSQL syntax. Google's official BigQuery lexical structure and syntax documents identifiers, literal variants, parameters, comments, case sensitivity, and reserved keywords.
Formatting SQL Server T-SQL
SQL Server's Transact-SQL commonly uses square brackets for delimited identifiers, @ variables, # temporary table names, TOP, table hints, and procedural control flow. Double-quoted identifier behavior depends on QUOTED_IDENTIFIER. Unicode string constants conventionally use an N prefix. These characters need lexical treatment before a formatter decides how to space an expression.
Pagination differs visibly from the other three dialects. TOP (25) restricts a query near SELECT. Offset pagination uses ORDER BY ... OFFSET ... ROWS FETCH NEXT ... ROWS ONLY. Replacing either form with LIMIT is a translation, not formatting. A formatter must also keep table hints and OPTION query hints in their correct structural positions.
DECLARE @start_time datetime2 = '2026-08-01T00:00:00';
SELECT
o.[order],
JSON_VALUE(o.payload, '$.customer.id') AS customer_id,
o.created_at
FROM sales.orders AS o
WHERE o.created_at >= @start_time
ORDER BY o.created_at DESC
OFFSET 50 ROWS
FETCH NEXT 25 ROWS ONLY;
GO is especially easy to misunderstand. It is recognized as a batch separator by tools such as SQL Server Management Studio and sqlcmd; it is not a Transact-SQL statement sent to the server in the same way as SELECT. A formatter that supports scripts may preserve and align batches, while a formatter for one server statement may reject the marker. The SQL Server Formatter targets T-SQL layout. Microsoft's official Transact-SQL syntax conventions explains statement notation, multipart names, terminators, and documented applicability across SQL Server products.
How to choose the correct formatter dialect
- Identify the execution target. Use the database product, major version, compatibility level, and SQL mode from the application configuration or connection—not a guess based on one keyword.
- Separate generated templates from executable SQL. dbt, Jinja, application placeholders, migration directives, and ORM annotations may exist before compilation but never reach the database. Choose a formatter that understands the template layer or format the compiled SQL.
- Preserve comments and hints. Comments can carry optimizer hints, version gates, migration metadata, or review explanations. Treat unknown comment-like forms as content rather than deleting them.
- Confirm procedural scope. LiveParse does not support stored procedures or custom-delimiter scripts, including MySQL
DELIMITERdirectives. Use engine- and client-aware tooling for routines, scripting blocks, and batch commands. - Pin a formatter version in automation. Layout algorithms and grammar support evolve. A pinned version prevents an upgrade from rewriting an entire repository without an intentional review.
If the source is genuinely portable SQL, the generic online SQL Formatter is a practical starting point. Once a query uses engine-specific syntax, select its matching dialect. Do not create several files formatted under different modes and assume the prettiest output identifies the correct database.
A safe formatting workflow
Formatting is most reliable when it is a reversible review step rather than a silent mutation. Start from version-controlled or otherwise recoverable source. Select the known dialect and explicit style options. Format, then inspect a whitespace-aware and token-aware diff. The changed output should retain every literal, identifier, placeholder, comment, hint, and statement in the same logical order.
- Save the original SQL and record the intended engine and version.
- Choose keyword case, indentation, expression width, and blank-line policy. LiveParse does not expose a comma-style control.
- Format locally when the query may contain production names, filters, customer identifiers, or proprietary logic.
- Review the diff, paying special attention to quotes, comments, hints, parameters, operators, and batch boundaries.
- Run the engine's parser, linter, migration check, or prepare mechanism where appropriate.
- Use
EXPLAINor execute only under the permissions, parameters, transaction controls, and isolated data environment suitable for that query. - Run application tests that assert results and side effects, not merely successful parsing.
Do not paste a destructive statement into a production console just to validate formatting. Parsing and planning can also have permissions or locking implications depending on the engine and statement. Use the organization's established database review path. For generated SQL, keep tests against representative outputs so formatter upgrades encounter nested expressions, comments, parameters, and every supported dialect feature.
Format SQL in your browser. Start with the general SQL formatter, or open the dialect-specific workspace for MySQL, PostgreSQL, BigQuery, or SQL Server. Formatting runs as a presentation step; database validation and execution remain under your control.
Open the SQL FormatterSQL formatting review checklist
- Dialect: Does the selected mode match the actual database, version, and compatibility settings?
- Strings: Are quote delimiters, prefixes, escapes, dollar tags, raw markers, and string contents unchanged?
- Identifiers: Are backticks, double quotes, brackets, qualification, and case preserved?
- Comments and hints: Did every comment remain in the intended statement and position?
- Parameters: Are
?,:name,@name,$1, and template placeholders still intact? - Operators: Were multi-character and dialect-specific operators kept as single meaningful tokens?
- Boundaries: Does the input avoid unsupported stored procedures, custom delimiter directives, and client batch markers? Are ordinary semicolon-delimited statements unchanged?
- Scope: Did the tool format only the SQL language layers it actually supports?
- Verification: Was correctness checked independently through review, engine-aware validation, and tests?
Frequently asked questions
Can one SQL formatter handle every database?
One interface can support several dialects, but it still needs separate lexical and grammar rules behind each mode. A lowest-common-denominator formatter may handle simple queries, yet it cannot safely infer every vendor extension. Select the target explicitly and verify that the formatter version supports the constructs in the input.
Does formatting SQL change how it runs?
Whitespace and keyword case changes outside quoted content normally preserve meaning, but a faulty or mismatched formatter can alter tokens, comments, hints, template expressions, or statement boundaries. Always inspect the diff. Any tool that rewrites expressions, converts functions, changes pagination, or replaces identifier quotes is performing translation or refactoring, not merely formatting.
Does a SQL formatter validate syntax?
Not necessarily. Some formatters use parsers and can report certain syntax errors; others deliberately tolerate incomplete SQL. Neither behavior proves acceptance by the target database. Exact syntax depends on engine version and settings, while name resolution, types, privileges, and runtime behavior require more context than a formatter has.
Can formatting prove that a query is safe?
No. A cleanly formatted statement can contain SQL injection, excessive access, a destructive operation, an unbounded scan, a Cartesian join, or a subtle authorization failure. Use parameter binding, least privilege, code review, query planning, resource controls, and application tests. Formatting only makes the text easier to inspect.
Should SQL keywords be uppercase?
Uppercase keywords are a common convention, not a universal semantic requirement. Lowercase keywords can be equally readable when applied consistently. Configure the team's preferred style, but never apply case changes to string contents or quoted identifiers and avoid guessing whether an ambiguous word is a keyword without dialect context.
Should commas be leading or trailing?
Both styles can be readable. Trailing commas resemble many programming languages; leading commas can make selected-column diffs visually obvious. Choose one policy when your formatter exposes that option. LiveParse currently follows its formatting engine's comma layout and does not offer a leading-versus-trailing comma control. Dialect validity still takes precedence, particularly in contexts where a trailing comma is or is not accepted.
Can LiveParse format stored procedures or custom-delimiter scripts?
No. LiveParse's SQL formatters do not support stored procedures or custom-delimiter scripts, including MySQL DELIMITER directives. Use engine- and client-aware tooling for routines, procedural bodies, deployment scripts, and batch commands.
How should templated SQL be formatted?
Use a formatter that understands both the template language and the SQL dialect, or format the compiled SQL for diagnostics. A generic SQL tokenizer may interpret template braces, control blocks, or macros as operators and identifiers. Do not overwrite the template from compiled output because comments, macros, source mappings, and abstractions may be lost.
Which dialect should I select for Amazon-compatible or cloud databases?
Select the documented language of the actual service rather than the vendor it resembles. Cloud warehouses and compatible databases often start from PostgreSQL, MySQL, or another grammar and then add or remove syntax. Use a dedicated dialect when available; otherwise document the closest supported mode and review unsupported extensions carefully.
Primary references
- MySQL 8.4 Reference Manual: Language Structure — official rules for literals, identifiers, keywords, expressions, and comments.
- MySQL 8.4 Reference Manual: Comments — line comments, block comments, executable version comments, and optimizer-hint comments.
- PostgreSQL: Lexical Structure — official documentation for tokens, identifiers, constants, dollar quoting, comments, and operators.
- BigQuery GoogleSQL: Lexical Structure and Syntax — official rules for identifiers, literal forms, parameters, comments, and reserved keywords.
- Microsoft Transact-SQL Syntax Conventions — official reference notation, multipart names, statement terminators, and product applicability.
- Microsoft: GO command — the client-tool batch separator and its distinction from a Transact-SQL statement.