oktools
Security
Data
API
Converters
Images
Generators
oktools
Security expand_more
password
Password Generator
Generate strong random passwords.
lock
Hash Generator
Generate MD5, SHA-1, SHA-256, SHA-512 hashes.
verified_user
JWT Decoder
Decode and inspect JSON Web Tokens.
workspace_premium
SSL Certificate & CSR Decoder
Decode X.509 certificates, chains and CSRs.
Data expand_more
code
JSON Formatter & Validator
Format and validate JSON.
database
SQL Formatter & Beautifier
Format and minify SQL queries.
difference
JSON Compare (Diff)
Compare two JSON documents.
regular_expression
Regex Tester & Explainer
Test regular expressions and see what they do.
event_repeat
Cron Expression Parser
Decode cron expressions and preview run times.
compare_arrows
Text Diff & Compare
Compare two texts line by line.
API expand_more
api
OpenAPI & Swagger Validator
Validate OpenAPI specs and inspect endpoints.
send
Online API Client
Send HTTP requests like Postman, in your browser.
rule
JSON Schema Validator
Validate JSON against a schema, or generate one.
dataset
Mock Data Generator
Fake JSON data from a schema or an example.
lan
HAR File Viewer
Inspect and sanitise browser HAR files.
pin
HTTP Status Codes
Every HTTP status code, explained.
Converters expand_more
code
Base64 Encoder/Decoder
Encode and decode Base64 text/files.
link
URL Encoder/Decoder
Encode URLs and query parameters.
access_time
Unix Timestamp Converter
Convert Unix timestamps to readable dates.
swap_horiz
CSV ↔ JSON Converter
Convert between CSV and JSON.
data_object
JSON ↔ YAML ↔ TOML Converter
Convert between JSON, YAML and TOML.
tag
Number Base Converter
Convert binary, octal, decimal and hex.
palette
Color Converter & Contrast Checker
Convert HEX, RGB, HSL, OKLCH and check WCAG contrast.
straighten
Unit Converter
Convert kg to lbs, cm to inches, miles to km and more.
public
Time Zone Converter
Convert times between time zones and cities.
Images expand_more
photo_size_select_large
Image Compressor & Converter
Compress, resize and convert images.
crop
Image Cropper & Resizer
Crop, rotate and resize images to exact sizes
web_asset
Favicon Generator
Make favicon.ico, PNG, SVG and manifest icons from an image or text
image_search
EXIF Viewer & Remover
View and strip photo metadata and GPS location
Generators expand_more
credit_card
Credit Card Number Generator (test numbers only)
Generate valid-format test card numbers (non-functional).
format_list_numbered
UUID Generator
Generate UUID/GUID values.
pin
SSN Generator
Generate fake Social Security Numbers with names.
text_fields
Lorem Ipsum Generator
Generate placeholder text.
qr_code_2
QR Code Generator
Create QR codes for links, Wi-Fi, contacts and more.
Home->Data->SQL Formatter & Beautifier
database

SQL Formatter & Beautifier

Paste a SQL query to beautify it with one clause per line, nested subqueries and the keyword case you prefer, or minify it to a single line for code and config files. Supports PostgreSQL, MySQL, SQL Server, Oracle, BigQuery, Snowflake and more dialects. Everything runs in your browser; nothing is uploaded.

Format:
input

How it works

Pretty mode runs the open-source sql-formatter library with the dialect you pick. It first splits the text into tokens using that dialect’s rules — which quote marks open a string or a name, which characters form an operator, whether $1, ? or :name is a parameter — and then parses the tokens into clauses, expressions and nested brackets. The layout is printed from that structure rather than by finding keywords in the text, which is why a column called "from" inside double quotes or the word select inside a string is left alone. Keyword case applies to keywords, function names and data types together; identifiers and literals are printed exactly as typed.

Minify mode does not parse at all, so it works on any SQL, including statements the formatter cannot read. It walks the text once, copying strings, quoted identifiers, T-SQL [bracketed names] and PostgreSQL $$-quoted function bodies byte for byte, dropping -- and /* */ comments, and collapsing all other whitespace to single spaces before removing the ones next to commas, semicolons and brackets. Each dialect’s quirks are respected: a backslash escapes a quote in MySQL and BigQuery strings, # starts a comment in MySQL, and there -- counts as a comment only when a space follows it, so 5--1 stays arithmetic.

The output follows the input on every keystroke. When the formatter cannot place a token, the error names the first word it stopped at with its line and column, instead of the grammar dump the library produces. Use output as input moves the result into the input box so further edits start from the clean copy, and Clear All empties it while keeping the dialect, case and indent you chose.

Examples

Pretty-print a one-line query from a log

Each clause starts a line and its items step in by two spaces. The join stays under FROM with its ON condition, COUNT is upper-cased with the keywords, and the date string is untouched.

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.created_at >= '2026-01-01' group by u.id, u.email having count(o.id) > 5 order by orders desc limit 20
Output
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.created_at >= '2026-01-01'
GROUP BY
  u.id,
  u.email
HAVING
  COUNT(o.id) > 5
ORDER BY
  orders DESC
LIMIT
  20

Minify a commented query for a string in code

Both comments are gone and the subquery’s brackets close up, while the spaces around = and the keyword TRUE are kept. The result runs exactly as the original did.

Input
-- active customers with a recent order
SELECT c.id,
       c.name
FROM customers c
WHERE c.active = TRUE /* soft-deleted rows are FALSE */
  AND EXISTS (
    SELECT 1 FROM orders o WHERE o.customer_id = c.id
  );
Output
SELECT c.id,c.name FROM customers c WHERE c.active = TRUE AND EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Format PostgreSQL with its own dialect

With Standard SQL selected this query stops at the cast: Unexpected "::text[]" at line 1, column 35. With PostgreSQL selected, the ->> operator, the :: cast and the $1 placeholder are all recognised, and the type name is upper-cased with the keywords.

Input
select data->>'name' as name, tags::text[] from items where id = any($1)
Output
SELECT
  data ->> 'name' AS name,
  tags::TEXT[]
FROM
  items
WHERE
  id = ANY ($1)

Find the bracket that never closes

The subquery opens a bracket on the way in and the statement ends before it is closed, so the formatter reports the end of the text as the place it gave up.

Input
SELECT name FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100
Error
The SQL ends unexpectedly at line 1, column 81: a bracket, quote or clause is not closed.

Supported formats

  • Twenty SQL dialectsStandard SQL, PostgreSQL, MySQL, MariaDB, SQLite, SQL Server (T-SQL), Oracle PL/SQL, BigQuery, Snowflake, Redshift, DuckDB, ClickHouse, Spark, Hive, Trino/Presto, Db2, Db2 for i, TiDB, SingleStore and N1QL, each with its own quoting, operators, comments and parameter styles.
  • Any statement, several at a timeSELECT with CTEs, joins, subqueries, window functions and CASE; INSERT, UPDATE, DELETE and MERGE; CREATE, ALTER and DROP. Several statements separated by semicolons are formatted one after another with a blank line between them.
  • Pretty output with your choice of styleIndent by 2 spaces, 4 spaces or a tab, and print keywords, functions and types in UPPER case, lower case or as typed. Minify writes one line with comments removed.
  • Placeholders and commentsPositional ? and $1, named :name and @name parameters are kept as written, in the dialects that use them. Comments are kept in Pretty mode and removed in Minify, apart from /*+ */ hints and /*! */ MySQL executable comments.

Use cases

  • Read a query captured from an ORM or a slow-query logHibernate, Django, ActiveRecord and pg_stat_statements all hand you SQL on one long line. Formatting it shows the joins and conditions clause by clause, which is where a missing index or a cartesian join becomes visible.
  • Tidy SQL before a code review or a migration commitConsistent indentation and keyword case make a diff show what changed in the query instead of who wrote it, and keep migration files readable months later.
  • Embed a query in code, a config file or a JSON payloadMinify turns a readable, commented query into the single line that fits in a string literal, an environment variable or a JSON field — then the JSON Formatter can check the document around it.
  • Share a query in a ticket or a chatFormat it, copy it into a code block and the person reading it can follow the logic without reformatting it themselves.

Limitations

  • Not a validatorIt knows SQL’s shape, not your schema: misspelt columns, missing tables, type mismatches and many grammar errors format without complaint. Only the database can tell you a query is valid.
  • Procedural code is laid out looselyPL/pgSQL, PL/SQL and T-SQL blocks with IF, LOOP, DECLARE or BEGIN … END are tokenised correctly but not indented as program structure, and a $$-quoted function body is printed as written.
  • Some vendor syntax is printed as a clauseLess common constructs can land on a line of their own: T-SQL’s WITH (NOLOCK) table hint, for example, is laid out as if it were a WITH clause. The query is unchanged; only its layout is unusual.
  • Minify trusts the dialect choiceMinify removes what the chosen dialect treats as a comment. With the wrong dialect selected — # text in a PostgreSQL query, for example — it can keep or drop the wrong span, so pick the right one before minifying.
  • The layout is fixedThere is no option to keep short clauses on one line, put commas first or align columns. For a house style with those rules, use a configurable formatter such as sqlfluff in your editor or CI.

Related tools

codeJSON Formatter & ValidatorFormat and validate JSON.arrow_forwardswap_horizCSV ↔ JSON ConverterConvert between CSV and JSON.arrow_forwardcompare_arrowsText Diff & CompareCompare two texts line by line.arrow_forward

Frequently asked questions

How do I format a SQL query?

Paste the query into the input box and the formatted version appears below it as you type: every clause — SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY — starts a line of its own, the columns and conditions under it are indented one step, and subqueries and CASE expressions are nested a further step in. Copy the result with the button on the output card.

Which SQL dialects are supported?

Standard SQL, PostgreSQL, MySQL, MariaDB, SQLite, SQL Server (T-SQL), Oracle PL/SQL, BigQuery, Snowflake, Amazon Redshift, DuckDB, ClickHouse, Spark SQL, Hive, Trino/Presto, IBM Db2, Db2 for i, TiDB, SingleStore and Couchbase N1QL. Pick the one your query was written for: the dialect decides which quotes, operators, placeholders and keywords are recognised, so PostgreSQL’s :: casts or T-SQL’s [bracketed names] are only understood with their own dialect selected.

Why does my query show an error?

Usually because the dialect does not match. A PostgreSQL cast such as tags::text[], a MySQL # comment or a T-SQL [column name] is not Standard SQL, so the formatter stops at the first character it cannot place and names its line and column. Choose your database in the Dialect list and the same query formats. If it still fails, the error points at a real problem — most often a bracket or a quote that is never closed.

Does the SQL formatter validate my query?

No, and it is worth knowing why. It checks that the text can be split into SQL tokens and laid out as clauses, but it does not know your tables, columns or types, and it accepts many statements a database would reject — a missing FROM, a misspelt column or a GROUP BY that leaves out a selected column all format without complaint. Run the query against the database, or EXPLAIN it, to know it is valid.

How do I minify SQL to a single line?

Choose Minify. Comments are removed, every run of spaces and line breaks becomes a single space, and the spaces beside commas, semicolons and inside brackets go, which is the form that fits in a string literal in code, a log line or a JSON config value. Text inside quotes is never touched, and optimizer hints written as /*+ ... */ or MySQL’s /*! ... */ are kept because the database reads them.

Can I keep my keywords lower case?

Yes. Keyword case offers UPPER, lower and Preserve. The choice covers keywords, function names such as COUNT and COALESCE, and data types such as INT and VARCHAR; table names, column names, aliases and string contents are always left exactly as you wrote them. Preserve leaves keywords as typed and changes only the layout.

Is my SQL sent to a server?

No. The formatter is JavaScript that runs in your browser, so the query — and any table names, customer IDs or literal values inside it — never leaves your machine, is not logged and is not attached to an analytics event. You can confirm it in the browser’s network tab, which stays empty while you work.

oktools

Privacy PolicyAbout UsFAQGuidesSuggest a Tool