SQL Formatter & Beautifier

Paste a query to format SQL for MySQL, PostgreSQL, SQL Server, Oracle, Snowflake, BigQuery and four more dialects, or minify it to one line. Errors show their line and column. Nothing is uploaded.

More options

Result

The formatted SQL appears here as you type. No query to hand? Pick one from Example…

Why format SQL?

SQL often arrives in the worst possible shape: one 2,000-character line copied from an application log, a query written in a hurry, a report a BI tool generated. Formatting puts each clause on its own line, indents subqueries and lines up conditions, so you can see what a query does, spot a join with no condition or an OR that needs brackets, and review a change line by line. This formatter reads ten SQL dialects, keeps your comments and template tags, and runs entirely in your browser, so queries that mention customers, salaries or credentials never leave your device.

How to format SQL

  1. Paste SQL, drop a .sql file on the box, or pick an example.
  2. Choose your database under Dialect. If the SQL can't be read, the error shows the line and column, and the dialects that can read it are one tap away.
  3. Set keyword case, indentation and blank lines between statements; the result updates as you type.
  4. Press Copy or Download, or switch to Minified for one line per statement.

What a SQL beautifier does: before and after

Here is a typical one-line query, the way it comes out of a log or an ORM, and the same query after formatting with the default settings (Standard SQL, upper-case keywords, 2-space indent). This page ran it through the formatter as it was built.

Before

select c.name, count(o.id) as orders, sum(o.total) as revenue from customers c left join orders o on o.customer_id = c.id and o.status <> 'cancelled' where c.country = 'US' and (c.vip = true or o.total > 500) group by c.name order by revenue desc;

After

SELECT
  c.name,
  COUNT(o.id) AS orders,
  SUM(o.total) AS revenue
FROM
  customers c
  LEFT JOIN orders o ON o.customer_id = c.id
  AND o.status <> 'cancelled'
WHERE
  c.country = 'US'
  AND (
    c.vip = TRUE
    OR o.total > 500
  )
GROUP BY
  c.name
ORDER BY
  revenue DESC;
  • Every clause (SELECT, FROM, WHERE, GROUP BY) starts a line, and what belongs to it is indented below.
  • Each selected column gets its own line, so a column added in a code review shows up as one changed line.
  • Joins sit under FROM with their ON conditions, and each AND or OR starts its own line.
  • The bracketed OR group is too long to stay inline, so it opens onto separate lines, which makes the precedence of AND and OR impossible to miss.
  • Keywords and function names are capitalised; table names, aliases and the string 'cancelled' are untouched.

SQL formatting conventions, and how to set them

There's no single official SQL style, but most style guides and teams agree on a handful of rules. This is how each one maps to the options above.

ConventionWhySetting here
Keywords in capitalsSELECT, FROM and JOIN stand out from table and column names. Lower case is just as valid; pick one per project.Keywords: UPPER, lower or As typed
One clause per lineThe shape of the query is visible at a glance.Always on
One column per line, comma at the endDiffs show exactly which column changed.Always on (trailing commas)
AND / OR leading the lineConditions line up and one can be commented out on its own.AND / OR: start or end of the line
Consistent indentationNesting depth is easy to follow.Indent: 2 spaces, 4 spaces or Tab
Short expressions stay inlineCOALESCE(a, b) or IN ('a', 'b') doesn't need five lines.Keep ( … ) on one line up to 50 characters
A blank line between statementsSeparates the steps of a script.Blank lines: none, 1 or 2
Aligned “river” layoutClause keywords form a column, and values start at the same position.Layout: Tabular, left- or right-aligned

The three layouts on one query, again produced by the formatter at build time:

Standard. Clause keywords on their own line, contents indented below.
SELECT
  id,
  name,
  total
FROM
  orders
WHERE
  status = 'paid'
  AND total > 100
ORDER BY
  total DESC
Tabular, left-aligned. Keywords in a column; every value starts at the same position.
SELECT    id,
          name,
          total
FROM      orders
WHERE     status = 'paid'
AND       total > 100
ORDER BY  total DESC
Tabular, right-aligned. Keywords right-aligned into a “river” of white space.
   SELECT id,
          name,
          total
     FROM orders
    WHERE status = 'paid'
      AND total > 100
 ORDER BY total DESC

Supported SQL dialects and their syntax

The dialect tells the formatter which quotes, comments, parameters and keywords your database uses. Pick the wrong one and SQL that runs fine on the server can't be read: [Order Date] is a column name in SQL Server but means nothing in MySQL. The keyword lists differ too, so QUALIFY is laid out as a clause in Snowflake and BigQuery.

DialectQuoted namesStringsCommentsParameters
Standard SQLGeneric ANSI-style rules; a safe choice when you don't know the database."name"`name`'text'--/* */?
MySQLBackslash escapes in strings; "double quotes" are strings, not names.`name`'text'"text"--#/* */?@var, @@var
PostgreSQLDollar-quoted function bodies, :: casts, nested comments."name"'text'$tag$text$tag$E'\n'--/* nested */$1
SQL Server (T-SQL)GO batch separators, #temp tables, N'unicode' strings."name"[name]'text'--/* nested */@name
SQLiteAccepts the quoting styles of several other databases."name"`name`[name]'text'--/* */??1:name@name$name
BigQuery`project.dataset.table` names, raw and triple-quoted strings.`name`'text'"text"'''text'''r'raw'--#/* */?@name@@var
Snowflake$$ strings, // comments, : paths into VARIANT data, @stages."name"'text'$$text$$--///* */$1$name@stage
Oracle PL/SQLq'[...]' quoting, :bind variables, --+ optimizer hints."name"'text'q'[text]'--/* */:1:name&var
Amazon RedshiftPostgreSQL-style syntax with #temp tables."name"'text'--/* */$1
MariaDBThe same quoting and comment rules as MySQL.`name`'text'"text"--#/* */?@var, @@var

Not sure which to pick? Leave it on Standard SQL and paste. If the SQL can't be read, the error lists the dialects that can, and one tap switches. Strings, quoted names and comments are never changed in any dialect.

How to minify SQL

Switch the result to Minified to squeeze a query into as little space as possible, for a code string, a log line or a chat message. Minify removes comments, turns every run of spaces and line breaks into one space, drops the space next to brackets, commas and semicolons, and starts each statement on a new line. It never touches the inside of strings, and it keeps optimizer hints (/*+ … */) and MySQL's /*! … */ comments, because those change how a query runs.

Before

-- Top customers this year
select customer_id, sum(total) as spend /* gross */
from orders
where created_at >= '2025-01-01' -- calendar year
group by customer_id
order by spend desc;

Minified

SELECT customer_id,SUM(total) AS spend FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id ORDER BY spend DESC;

Why SQL won't format: common errors and fixes

The formatter has to read SQL before it can lay it out, so it stops where it can't. Each snippet below was run through it; the red line and the explanation are exactly what the tool shows.

Square-bracket names in the wrong dialect

select [order date] from orders

✗ Unexpected "[order" at line 1, column 8

Names in [square brackets] are SQL Server (T-SQL) and SQLite syntax. Pick one of those dialects, or quote the name with double quotes.

Brackets are SQL Server's way of quoting a name. Choose SQL Server (T-SQL) and it formats; for other databases write "order date" in double quotes (or `order date` in MySQL).

A parenthesis that's never closed

select id, (price * qty from order_items

✗ Unclosed ( at line 1, column 12

This parenthesis is never closed. Add the missing ) or remove the (.

The parser only notices at the end of the query, but the tool points at the ( that has no partner. The same check finds a stray ) with no ( before it.

A quote inside a string

select * from users where name = 'O'Brien'

✗ Unexpected "'" at line 1, column 42

This string never ends: add the closing '. To put a quote inside a string, type it twice ('it''s') or escape it as \'.

The string ends at the apostrophe in O'Brien, so the final quote opens a new string that never ends. Double the apostrophe: 'O''Brien'.

CASE without END

select case when total > 100 then 'big' from orders

✗ Unexpected "from" at line 1, column 41

A CASE expression is missing its END. Every CASE ... WHEN ... THEN ... ELSE ... closes with END before the next clause.

Every CASE expression closes with END, so the parser stops at FROM. Write CASE WHEN total > 100 THEN 'big' END.

Curly quotes from a document

select * from orders where note = ‘urgent’

✗ Unexpected "‘urgent’" at line 1, column 35

Curly quotes come from word processors, slides and chat apps, and SQL doesn't read them as quotes. Replace them with straight ' and " quotes.

Word processors, slide decks and chat apps turn ' into ‘ ’. Paste SQL from a plain-text source, or replace the curly quotes with straight ones.

Formatting SQL in your editor or on the command line

  • VS Code has no SQL formatter built in. Install a SQL formatting extension, then run Format Document: Shift+Alt+F on Windows, Shift+Option+F on a Mac, Ctrl+Shift+I on Linux.
  • DBeaver: select the query and press Ctrl+Shift+F (Format SQL).
  • DataGrip and other JetBrains IDEs: Reformat Code, Ctrl+Alt+L, or Option+Command+L on a Mac.
  • Command line: the library behind this page has its own CLI. npx sql-formatter -l postgresql query.sql prints the formatted file, and --fix rewrites it in place.

The page is quicker when the SQL is somewhere else: an application log, a ticket, a dashboard's query panel or a colleague's message. It's also handy for SQL embedded in code: format it here, then paste it back.

More developer tools

API responses and config files have their own formatters: the JSON formatter validates and pretty-prints JSON with exact error positions, and YAML Lint checks YAML configs. To shrink front-end code rather than queries, use the HTML, CSS and JavaScript minifier. Comparing two versions of a query? Format both, then paste them into Text Diff so only real changes show. Turning a list of IDs into an IN (…) list is a job for Remove Line Breaks with commas, and query results exported as CSV become JSON with the CSV to JSON converter. For values inside queries, the Unix timestamp converter shows the SQL to convert epochs in each database, and the UUID generator makes test keys.

Frequently asked questions

How do I format a SQL query online?

Paste the query into the box (or drop a .sql file on it) and choose your database under Dialect. The formatted SQL appears as you type, with one clause per line, indented subqueries and colour-coded keywords. Press Format SQL to jump to the result on a phone, then Copy it or Download .sql. Keyword case, indentation and blank lines between statements apply as soon as you change them.

Is my SQL uploaded or stored anywhere?

No. Formatting runs in your browser, in a background worker, using the open-source sql-formatter library, so your queries never leave your device. That matters when they mention customer data, salaries or credentials. Your settings are remembered in this browser, and the text in the box is kept only for the current tab so a reload doesn't lose it; closing the tab clears it.

Which SQL dialects does this formatter support?

Ten: Standard SQL, MySQL, MariaDB, PostgreSQL, Microsoft SQL Server (T-SQL), SQLite, Google BigQuery, Snowflake, Oracle PL/SQL and Amazon Redshift. The dialect decides which quotes, comments, parameters and keywords are understood: [square bracket] names work in SQL Server and SQLite, # comments in MySQL, MariaDB and BigQuery, and $1 parameters in PostgreSQL and Redshift. If your SQL can't be read in the dialect you picked, the tool lists the dialects that can read it.

Does formatting change what my query does?

No. Only whitespace, line breaks and the letter case of keywords, function names and data types change; strings, quoted names, numbers, comments and the order of everything stay as written. SQL keywords are case-insensitive, so changing their case is safe. One thing to check: a table or column named like a keyword (month, user) is capitalised along with the keywords, so in databases with case-sensitive table names, such as MySQL on Linux and BigQuery, quote those names or choose Preserve.

Should SQL keywords be uppercase or lowercase?

Either works, because keywords are case-insensitive in every major database. Upper-case keywords (SELECT, FROM, WHERE) are the traditional style and make a query's structure stand out from table and column names; many analytics teams write everything in lower case because it's quicker to type. What matters is being consistent within a project. Choose UPPER, lower or Preserve under Keywords; function names and data types follow that choice unless you set them separately under More options.

How do I minify SQL or put a query on one line?

Switch the result to Minified. Comments are removed, every run of spaces and line breaks becomes a single space (or none next to brackets, commas and semicolons), and each statement goes on its own line, so a single query becomes one line. Text inside strings keeps its spaces and line breaks. Optimizer hints such as /*+ INDEX(...) */ and MySQL's /*! ... */ comments are kept, because they change how the query runs.

Why does the formatter say "Unexpected" or "Unclosed ("?

To lay SQL out, the formatter has to read it, and it stopped at that point. The usual causes are the wrong dialect (square bracket names need SQL Server or SQLite, backticks need MySQL, MariaDB, BigQuery or SQLite), a string or parenthesis that's never closed, a CASE without END, and curly quotes pasted from a document. The message gives the line and column with a caret, Jump to error puts your cursor on it, and the dialects that can read the SQL are offered as one-tap switches.

Does this check my SQL for syntax errors?

Partly. It finds problems that stop SQL being read, such as an unclosed parenthesis or quote, and shows exactly where they are. It doesn't know your tables or every rule of your database, so SQL that formats cleanly can still fail when it runs: a misspelt column, a column missing from GROUP BY or a function your database doesn't have only show up on the server. To have the database itself check a query without running it, use EXPLAIN (PostgreSQL, MySQL, SQLite, Oracle's EXPLAIN PLAN), the estimated execution plan in SQL Server, or a dry run in BigQuery.

Can it format stored procedures, PL/SQL blocks or T-SQL scripts with GO?

T-SQL scripts with GO work: the script is split at each GO line, the way SQL Server Management Studio and sqlcmd split batches, each batch is formatted, and GO stays on its own line. Procedures, functions, triggers and BEGIN ... END blocks are formatted statement by statement, but the formatting library doesn't understand procedural code, so IF, WHILE and DECLARE blocks get only basic layout. MySQL scripts that change the DELIMITER can't be read; format the statements inside them on their own.

Can I format dbt or Jinja templated SQL?

Yes. With Keep template tags on (the default, under More options), {{ ... }}, {% ... %}, {# ... #} and ${...} tags are set aside while the SQL is formatted and put back exactly as written, so {{ ref('orders') }} can stand in for a table name. Block tags such as {% if is_incremental() %} that were on a line of their own stay on a line of their own. Choose your warehouse's dialect, such as Snowflake, BigQuery, Redshift or PostgreSQL.

Can I put commas at the start of each line?

Not with this formatter: it always puts commas at the end of the line (trailing commas), the style most formatters use. Leading commas make the last column easier to comment out and a missing comma easier to spot, and some teams prefer them; in that case, format here for the indentation and move the commas in your editor.

How do I stop part of my SQL from being reformatted?

Put the comment /* sql-formatter-disable */ before it and /* sql-formatter-enable */ after it. Everything between the two is copied exactly as written and isn't even parsed, which is handy for a hand-aligned VALUES list or for syntax the formatter can't read.

Advertisement