Converter tool

SQL Formatter

Turn a one-line or messy query into readable SQL with each clause on its own line, or squeeze it onto one line. Strings and comments come through untouched.

Pasted text0 B / 2 MB

Handles generic SQL with common PostgreSQL, MySQL, SQL Server and SQLite syntax. Only whitespace and keyword case change: text inside quotes, quoted names and comments is copied exactly, and syntax the formatter does not recognise is left as typed. Your SQL is formatted on this page and is not sent to a server.

Preview

Output Preview

Paste SQL or open a file, then press Format or Minify. Changing an option afterwards updates the result.

SQL Formatter

Operator: Abdulla Al Fahad. How tools are built and checked

SQL rarely arrives in a readable state. An ORM writes its queries to the log as one long line, a reporting tool hides a 40-line query behind a single text field, and a colleague pastes a statement into chat with every line break gone. Finding the join condition or the forgotten filter in 600 characters of unbroken text is slow, and it is where mistakes slip through review.

This formatter rebuilds the layout. Every major clause starts its own line, the columns of a SELECT list can go one per line, JOINs sit under FROM with their ON condition, subqueries and CASE expressions are indented as blocks, and keywords take the case you pick. The reverse button squeezes a query onto one line for a config file or a code string. In both directions only whitespace and keyword case change: the text inside quotes, quoted names and comments is copied character for character.

Key features

  • Line breaks before WITH, SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, UNION, INSERT INTO, VALUES, UPDATE, SET, DELETE and RETURNING
  • JOIN variants indented under FROM, with extra join conditions one step deeper
  • Each top-level AND and OR in WHERE and HAVING on its own line, while BETWEEN x AND y stays together
  • Subqueries in parentheses and CASE ... WHEN ... END laid out as indented blocks
  • Keyword case: UPPER, lower or exactly as typed
  • One column per line, with the comma at the end of the line or at the start of the next
  • Several statements kept apart with a blank line between them
  • Minify to a single line, optionally dropping comments
  • Warnings with line numbers for unclosed quotes and comments and unmatched parentheses

Which SQL syntax passes through intact

Input is plain SQL text, pasted or loaded from a .sql or .txt file of up to 2 MB. Scripts saved as UTF-8 work best. If your editor wrote the script in UTF-16, the marker bytes at its start tell the formatter so; anything that fails to decode as UTF-8 falls back to Windows-1252, the code page older Windows editors saved scripts in. One statement or a whole script works; statements are told apart by their semicolons, and a GO line between SQL Server batches is recognised and kept on its own line.

The tokenizer knows the quoting rules of the four common dialects: 'single-quoted' strings with doubled quotes inside, PostgreSQL E'...' strings with backslash escapes, N'...' and X'...' literals, dollar-quoted bodies such as $$...$$ or $fn$...$fn$, and names quoted with double quotes, backticks or [square brackets]. Comments written with --, /* */ or a MySQL # followed by a space are kept where they were. Placeholders such as ?, $1, :name, @var and %s, and template tags like {{ ref('orders') }} or {% if %}, pass through whole, so a parameterised query or a dbt model still works after formatting.

Pick the indent step that matches your codebase: two spaces, four spaces or one tab character for each level of nesting. A formatted download keeps the source file's name with .formatted.sql at the end, a minified one gets .min.sql, and both finish with a line break.

How it works

The SQL is first cut into tokens: words, numbers, quoted strings, quoted names, comments, operators and punctuation. Formatting then rebuilds only the gaps between tokens. Where a layout rule applies, the gap becomes a line break and indent; where none applies, it becomes one space, or stays empty if the source had nothing there. That fallback is what keeps unfamiliar syntax, such as a vendor-specific operator or an array subscript like tags[1], looking the way it was typed.

Clause keywords sit at the left edge of their block and their contents are indented one step below them. A parenthesis whose first word is SELECT, WITH or VALUES opens a new block one step further in, and its closing parenthesis returns to the line's indent so an alias such as ) AS recent follows it. Parentheses that contain a CASE get their own lines as well; all other parentheses, such as function arguments, IN lists and OVER (PARTITION BY ...) windows, stay on one line.

Statements that are not queries are handled more gently. CREATE TABLE puts each column definition on its own line, but ALTER TABLE, GRANT, CREATE INDEX and similar statements only get keyword case and tidy spacing, because words like SELECT, UPDATE and DELETE are privileges or rule actions there, not clauses. A CREATE VIEW ... AS SELECT switches to the query layout from the SELECT onwards.

Minify works on the same tokens. Runs of whitespace collapse to a single space, and the space disappears next to commas, parentheses and operators unless removing it would join two tokens into something else. For example, 1 - -1 keeps a space so it never becomes 1--1, which would turn the rest of the line into a comment, and a kept -- comment is always followed by a line break.

Common use cases

  • Reading a slow query copied from a database log before adding an index
  • Cleaning up a query before pasting it into a pull request or a ticket
  • Making a long SELECT from a BI tool's text field reviewable line by line
  • Squeezing a query onto one line for a YAML config, an environment variable or a code string
  • Giving a team's scripts one keyword case and indent so diffs show real changes only
  • Checking where an unbalanced quote or parenthesis begins in a statement that will not run

How to use this tool

  1. Paste the SQL into the box, drop a .sql file on it, or press Use sample to try a reporting query with a CTE and a CASE.
  2. Choose the keyword case, the indent and where commas go; leave one column per line on for long SELECT lists.
  3. If the code comes from MySQL and uses \' inside strings, tick the backslash escapes box so those quotes are read correctly.
  4. Press Format. Read any warnings above the result: they name the line where a quote or comment was never closed.
  5. Copy the result or download it. For a one-line version, press Minify instead, with or without comments.

Example

One-line query from an application log (uppercase keywords, 2-space indent)

select c.name, sum(o.total) as spent -- paid orders only
from customers c join orders o on o.customer_id=c.id and o.status='paid' where o.placed_at>='2026-07-01' and c.country in ('PT','ES') group by c.name having sum(o.total)>500 order by spent desc limit 10;

Formatted (the comment stays on the line it described)

SELECT
  c.name,
  SUM(o.total) AS spent -- paid orders only
FROM
  customers c
  JOIN orders o ON o.customer_id = c.id
    AND o.status = 'paid'
WHERE
  o.placed_at >= '2026-07-01'
  AND c.country IN ('PT', 'ES')
GROUP BY
  c.name
HAVING
  SUM(o.total) > 500
ORDER BY
  spent DESC
LIMIT
  10;

Tips for best results

  • Format before you diff two versions of a query. Once both have the same layout, the diff shows the changed condition rather than every moved line break.
  • Turn off one column per line when the select list is short; the columns then share a single line under SELECT.
  • Leading commas (, b at the start of the line) make it easy to comment out the last column without breaking the one above it.
  • If a warning says a string never closes, check the named line and the lines above it: the real fault is often an earlier quote, such as the apostrophe in O'Brien.
  • Minify keeps comments unless you ask otherwise; drop them before putting a query into a single-line setting, where a -- comment would swallow the rest.

Common pitfalls

Backslashes are the classic trap. In standard SQL and PostgreSQL, 'C:\' is a complete string ending in a backslash; in MySQL's default mode, \' is an escaped quote and the string carries on. The formatter follows the standard rule unless you tick backslash escapes, and it warns when it sees a string ending in a backslash.

A /* comment that contains another /* is read differently by different databases: PostgreSQL and SQL Server nest such comments, MySQL and SQLite end at the first */. The formatter ends at the first */ and says so in a warning.

Procedural code gets case and spacing but no structure. IF ... THEN, loops and BEGIN ... END blocks in PL/pgSQL or T-SQL are not indented as blocks, and a dollar-quoted function body is a string, so it is left exactly as written.

A MySQL script that switches the statement terminator with DELIMITER // is not understood: the semicolons inside the procedure body still split it into separate statements in the layout, although no characters are lost.

There is no line-width limit. A long IN list or a function call with many arguments stays on one line, however wide it gets.

This is a formatter, not a validator. A misspelt keyword or a missing comma is laid out as best it can be; only unclosed quotes and comments and unmatched parentheses are flagged.

Common errors and how to fix them

"A quoted string that starts here is never closed"
The tokenizer reached the end of the text inside a quote, so everything after the named line was copied without formatting. Find the missing quote, often an apostrophe in a name such as O'Brien that needs doubling to O''Brien, fix it and format again.
"A quoted string ends with a backslash"
The query probably comes from MySQL, where \' means a quote inside the string. Tick Backslash escapes inside quotes and the last result is redone with that setting.
"This ) has no matching ( before it" or "The last statement leaves parentheses open"
The brackets do not pair up within one statement. Check the line given; a copied query that lost its first or last line is a common cause.
Your file is turned away as a binary, ZIP or PDF file
The SQL formatter only reads plain text. Save the query from your editor as .sql or .txt; for a workbook or document, copy the query text and paste it instead.

Best practices

  • Pick one keyword case and indent for a project and format every script with the same settings.
  • Keep comments next to the clause they explain; the formatter keeps an end-of-line comment on its line, so it stays attached when clauses move.
  • Format queries before review, minify only for places that need a single line, and keep the formatted copy as the one you edit.
  • Read the warnings even when the output looks fine; an unclosed quote can make the rest of a script look normal while leaving it unformatted.

Which words change case

Reserved words such as SELECT, WHERE, JOIN, NULL and CASE always follow the case option. Function names like count, sum, coalesce and date follow it only when a parenthesis comes straight after, because the same words are common column names: SELECT count FROM stats keeps count as typed, while count(*) becomes COUNT(*). Words that are often column names, such as name, status, type, value and data, are never touched.

Names also keep their case in the places where case can matter. A word directly after FROM, JOIN, INTO, UPDATE or TABLE is treated as a table name and kept as typed unless it is a reserved word such as LATERAL or ONLY, since MySQL on Linux compares table names case-sensitively; a word next to a dot (schema.table, t.column) is left alone; and an alias after AS keeps its case, because MySQL and SQL Server report that alias as the column name in the result.

Comments and the comma they sit beside

A comment at the end of a line stays at the end of that line, even when the line moves. When the source puts a comment before a comma, as in a -- first followed by , b on the next line, the trailing-comma layout writes a, -- first so the comma never ends up inside the comment. With leading commas, the comment stays after a and the comma starts the next line. Comments on their own lines stay on their own lines, in their original order.

  • -- and # comments always end their line, so no code is ever placed after them
  • Block comments inside a line stay inline; multi-line block comments keep their inner line breaks
  • Minify keeps MySQL /*! ... */ and optimizer hint /*+ ... */ comments even when comments are dropped, because they change what the statement does

Frequently asked questions

Can formatting change what my query does?

It changes only the whitespace between tokens and the letter case of keywords. Unquoted keywords are case-insensitive in PostgreSQL, MySQL, SQL Server and SQLite, and the text inside strings, quoted names and comments is never altered. Minify with Drop comments removes comments too, apart from the MySQL /*! */ and /*+ */ kinds that affect execution.

Which SQL dialect does it follow?

None in particular. It handles generic SQL with the common syntax of PostgreSQL, MySQL, SQL Server and SQLite, such as :: casts, backtick and bracket quoting, TOP, LIMIT and FETCH, and leaves syntax it does not recognise as typed.

Does running Format twice change the result?

For ordinary queries, formatting the output again with the same options gives the same text back. Comments placed in unusual spots, such as on their own line just before a semicolon, may move once more on a second run.

Can I paste a query that contains real customer data?

The query is tokenized and laid out by JavaScript on this page and is not sent to a server, and the formatter never stores it with localStorage or sessionStorage, so it exists only in the open tab. Formatting does not hide anything, though: values inside quotes, such as an email address in a WHERE clause, come out exactly as they went in, so remove them before you share the formatted query.