Ttooleras
🗃️

Format and beautify SQL queries for any dialect (MySQL, PostgreSQL, etc.). Free, private — all processing in your browser.

Samples:
Advertisement

The SQL Formatter takes messy, minified, or machine-generated SQL and produces clean, properly indented, easy-to-read queries. Whether you are debugging a slow query from an ORM, auditing stored procedures, reviewing a pull request, or preparing SQL for documentation, proper formatting makes complex queries navigable. Supports all major SQL dialects — MySQL, PostgreSQL, SQL Server (T-SQL), Oracle (PL/SQL), SQLite, BigQuery, Snowflake, Redshift, MariaDB — with dialect-specific keyword handling and syntax quirks.

Unformatted SQL is one of the biggest sources of bugs and slow code reviews. A 200-line query with no indentation, random capitalization, and inconsistent spacing is nearly impossible to audit. Formatted SQL reveals query structure: you can see JOINs lined up, WHERE conditions grouped, subqueries nested clearly, and CTEs organized logically. This formatter runs entirely in your browser — your SQL (which may contain schema details, table names, or sensitive query logic) is never uploaded. Configure indentation (2 spaces, 4 spaces, tabs), keyword case (UPPERCASE, lowercase, Capitalized), and comma placement (leading or trailing) to match your team's style guide.

SQL Formatter — key features

10+ dialects supported

Format SQL for MySQL, PostgreSQL, SQL Server, Oracle, SQLite, BigQuery, Snowflake, Redshift, MariaDB, and more. Dialect-specific keywords are recognized and preserved correctly.

Configurable keyword case

Choose uppercase (traditional, common), lowercase (modern style), or Capitalized (rare). Match your team's conventions.

Custom indentation

2 spaces, 4 spaces, or tab. Also configure how JOINs, subqueries, and CASE expressions are indented.

Leading or trailing commas

Leading commas (before each column) reduce Git diff noise when columns are added or removed. Trailing commas (after each column) look more natural to most developers. Pick your preference.

Format long WHERE and JOIN clauses

Complex conditions with many AND/OR are broken onto multiple lines with proper alignment for readability.

Preserve comments

Both line comments (`--`) and block comments (`/* */`) are preserved in their original positions.

Handle CTE and subquery nesting

WITH clauses and nested subqueries are indented to show their relationship clearly.

100% client-side

Your SQL never leaves the browser. Safe to format queries containing sensitive column names, schema details, or proprietary business logic.

How to use the SQL Formatter

  1. 1

    Paste your SQL

    Copy the SQL query from your IDE, database client, ORM log, or execution plan. Paste it into the input area.

  2. 2

    Select dialect

    Choose your database type (MySQL, PostgreSQL, SQL Server, etc.) so dialect-specific keywords are recognized correctly.

  3. 3

    Configure style

    Pick indentation (2/4 spaces or tab), keyword case (UPPER/lower), and comma placement (leading/trailing).

  4. 4

    Click Format

    The formatted query appears instantly. Structure and logic are now clearly visible.

  5. 5

    Copy back to your editor

    Click Copy to put the formatted query on your clipboard, or Download as a .sql file.

Common use cases for the SQL Formatter

Query debugging

  • Debug slow queries from EXPLAIN: Database query logs often contain unformatted SQL. Format to understand the query plan and identify missing indexes or expensive JOINs.
  • Inspect ORM-generated SQL: Rails ActiveRecord, Django ORM, SQLAlchemy, Prisma, TypeORM all generate SQL. Log the query, format it, and see what the ORM actually sent.
  • Review query hints and directives: SQL Server uses hints like WITH (NOLOCK); PostgreSQL has /*+ INDEX_SCAN */ — formatting makes these visible.

Code review

  • Review migration scripts: Before applying a schema migration, format the SQL for readability and run a review.
  • Audit stored procedures: Complex stored procedures are hard to read without formatting. Beautify to find bugs and logic errors.
  • Review AI-generated SQL: ChatGPT and other AI assistants generate SQL that often needs cleanup. Format to make it production-ready.

Documentation

  • Prepare SQL examples for docs: Format queries before including them in internal documentation, blog posts, or training materials.
  • Create style-guide-compliant samples: If your team has a SQL style guide, formatting enforces consistency.
  • Compare queries in diff tools: Formatted queries produce cleaner diffs — it is obvious what changed between versions.

Teaching and learning

  • Explain complex queries: When teaching SQL, formatted queries with clear indentation are far easier to explain than inline queries.
  • Learn by reformatting: Paste an unfamiliar query and format it — seeing the structure makes the logic clear.
  • Prepare exam or tutorial materials: Consistently-formatted SQL looks professional and is easier to study.

SQL Formatter — examples

Simple SELECT

Basic query with JOIN formatted for readability.

Input
SELECT u.id, u.name, COUNT(o.id) as orders FROM users u LEFT JOIN orders o ON u.id=o.user_id WHERE u.active=TRUE GROUP BY u.id,u.name ORDER BY orders DESC
Output
SELECT
  u.id,
  u.name,
  COUNT(o.id) AS orders
FROM
  users u
  LEFT JOIN orders o ON u.id = o.user_id
WHERE
  u.active = TRUE
GROUP BY
  u.id,
  u.name
ORDER BY
  orders DESC

WITH (CTE) query

Common Table Expression with nested subquery.

Input
WITH recent AS (SELECT user_id,COUNT(*) c FROM logins WHERE ts > NOW()-INTERVAL '7 days' GROUP BY user_id) SELECT u.name, r.c FROM users u JOIN recent r ON u.id=r.user_id
Output
WITH
  recent AS (
    SELECT
      user_id,
      COUNT(*) AS c
    FROM
      logins
    WHERE
      ts > NOW() - INTERVAL '7 days'
    GROUP BY
      user_id
  )
SELECT
  u.name,
  r.c
FROM
  users u
  JOIN recent r ON u.id = r.user_id

INSERT with many values

Bulk insert statement aligned.

Input
INSERT INTO products (id,name,price,stock) VALUES (1,'Widget',9.99,100),(2,'Gadget',19.99,50),(3,'Gizmo',29.99,25)
Output
INSERT INTO products (id, name, price, stock)
VALUES
  (1, 'Widget', 9.99, 100),
  (2, 'Gadget', 19.99, 50),
  (3, 'Gizmo', 29.99, 25)

CASE expression

Multi-branch CASE formatted cleanly.

Input
SELECT id, CASE WHEN age<18 THEN 'minor' WHEN age<65 THEN 'adult' ELSE 'senior' END AS bucket FROM users
Output
SELECT
  id,
  CASE
    WHEN age < 18 THEN 'minor'
    WHEN age < 65 THEN 'adult'
    ELSE 'senior'
  END AS bucket
FROM
  users

Leading commas style

Useful for Git diffs — adding/removing a column touches only one line.

Input
SELECT id, name, email, created_at FROM users
Output
SELECT
    id
  , name
  , email
  , created_at
FROM
  users

Lowercase keywords

Modern preference in some teams.

Input
SELECT * FROM Users WHERE email LIKE '%@tooleras.com'
Output
select
  *
from
  users
where
  email like '%@tooleras.com'

Technical details

SQL is a declarative language defined by the ISO/IEC 9075 standard (most recently updated in SQL:2023), but every database vendor implements dialects with unique extensions. A good formatter understands the common core plus vendor-specific keywords. This formatter supports:

Dialects:

- MySQL / MariaDB — Backtick identifiers, LIMIT with OFFSET, ENGINE/CHARSET options
- PostgreSQL — Double-quote identifiers, LIMIT with OFFSET, type casts, array syntax, JSON operators (->, ->>, @>)
- SQL Server (T-SQL) — Bracket identifiers, TOP N, IDENTITY, CROSS APPLY, OUTPUT clause
- Oracle (PL/SQL) — DUAL table, CONNECT BY, ROWNUM, (+) join syntax
- SQLite — Dynamic typing, WITHOUT ROWID
- BigQuery / Snowflake / Redshift — Analytic functions, standard SQL extensions
- DB2, Databricks, ClickHouse — Standard SQL with some extensions

Formatting rules applied:

1. Keywords — uppercase (SELECT, FROM, WHERE) by default. Lowercase option for teams that prefer it.
2. Indentation — major clauses (SELECT, FROM, WHERE, GROUP BY, ORDER BY) at the same level. Subqueries and CTE bodies indented.
3. Commas — leading (before the item) or trailing (after the item). Leading commas are a style that reduces diff noise when adding/removing columns.
4. Line wrapping — long expressions broken onto multiple lines aligned.
5. JOIN formatting — each JOIN on its own line, ON conditions aligned or on a new line.
6. Function calls — preserve formatting of function calls (e.g., COALESCE(a, b, c) on one line if short).
7. Comments-- line comments and /* */ block comments preserved.

Normalization:

The formatter normalizes whitespace but does not change semantics. It does not rewrite queries (e.g., does not convert subqueries to CTEs or change JOIN order). This makes it safe to use on production queries.

Validation:

This formatter handles valid and near-valid SQL. It does not fully validate — some syntax errors may pass through. For actual query validation, use EXPLAIN in your database or a linter like sqlfluff.

Common problems and solutions

Formatter does not validate semantics

A formatter produces clean-looking SQL from bad SQL too — it will not catch typos, wrong table names, or logic errors. Always run EXPLAIN or execute in a test environment.

Dialect mismatch

Format PostgreSQL SQL with MySQL dialect and you may lose PostgreSQL-specific syntax (JSON operators, array literals, CTE ... RETURNING). Choose the correct dialect before formatting.

Custom extensions and functions

Database-specific functions (PostgreSQL JSONB functions, SQL Server STRING_AGG, BigQuery struct syntax) may not format optimally. Check the output.

String literals with SQL inside

A string containing SQL-like text (dynamic query building, stored JSON with SQL) may get mis-formatted. Wrap such cases in clear quotes and review output.

Comment placement shifts

Inline comments may move to a different line due to reformatting. Not a bug — but can look surprising. For critical comments, use block comments placed strategically.

Overly long formatted output

A 500-column SELECT spread with leading commas becomes 1000+ lines. For queries that large, consider refactoring the schema or using views — formatting only goes so far.

Over-reliance on formatting for readability

Good SQL is readable at the logical level, not just the visual level. Use CTEs to break complex queries, alias tables meaningfully, and comment intent — formatting is the last mile, not the first.

Different formatter output across tools

Every formatter has its own style. If your team uses Prettier-SQL, VS Code SQL Formatter, or DBeaver's formatter, stick with one. Use this tool for quick ad-hoc formatting that matches those conventions reasonably.

SQL Formatter — comparisons and alternatives

SQL Formatter vs SQL Minifier: Formatting expands SQL for human reading; minifying compresses it to a single line. Minification is rarely useful — SQL is not sent over the wire like JavaScript is. Keep SQL formatted in code, store it in .sql files, and version control it.

This tool vs sqlfluff: sqlfluff is a CLI SQL linter and formatter with CI/CD integration and deep static analysis. This tool is for quick browser-based formatting without installation. Use sqlfluff in your build pipeline, this tool for ad-hoc cleanup.

This tool vs pgFormatter / MySQL Workbench formatter: Database vendor tools format SQL for their specific dialect. This tool supports multiple dialects in one place. For heavy PostgreSQL work, pgFormatter has deeper knowledge; for quick multi-dialect formatting, this tool is faster.

SQL Server vs PostgreSQL syntax: Same standard SQL core, but different extensions. SQL Server uses TOP N, [identifier], and SCHEMA.TABLE. PostgreSQL uses LIMIT N, "identifier", and schema.table. Choose the right dialect when formatting.

T-SQL vs PL/SQL: Microsoft's T-SQL (SQL Server) and Oracle's PL/SQL are procedural extensions to SQL. Stored procedures, functions, and triggers use them. This formatter handles both, but the logic inside procedures (IF/ELSE, loops) is formatted more heuristically than pure query SQL.

ANSI SQL vs dialect SQL: Some teams enforce ANSI-SQL-only code for portability. Others embrace dialect features for performance and clarity. The formatter respects both — it formats what you paste without rewriting to ANSI.

Frequently asked questions about the SQL Formatter

What is a SQL formatter?

A tool that takes SQL code — queries, stored procedures, schema definitions — and produces cleanly formatted output with consistent indentation, capitalization, and line breaks. Formatted SQL is far easier to read, review, and debug than minified or machine-generated SQL.

Which SQL dialects are supported?

MySQL, MariaDB, PostgreSQL, SQL Server (T-SQL), Oracle (PL/SQL), SQLite, BigQuery, Snowflake, Redshift, Databricks, ClickHouse, and more. Choose your dialect before formatting so dialect-specific keywords and syntax are recognized correctly.

Is it safe to format production queries with this tool?

Yes. The formatter runs entirely in your browser — no SQL is uploaded to any server. Safe for queries containing sensitive table names, schema information, or proprietary business logic. Open DevTools Network tab to verify no outbound requests.

Should I use UPPERCASE or lowercase SQL keywords?

UPPERCASE is the traditional convention — SELECT, FROM, WHERE stand out from column names. Most style guides (Mozilla, Simon Holywell's SQL Style Guide) recommend uppercase. lowercase is a modern preference for readability (less shouting). Both work — pick one and stick with it across your team.

What is the difference between leading and trailing commas?

Trailing commas (after each item): id, name, email — the default for most developers. Leading commas (before each item): id\n, name\n, email — reduces Git diff noise when adding or removing the last column (the delete/add affects only that line). Neither is objectively better; match your team's convention.

How does the formatter handle CTEs and subqueries?

CTEs (WITH name AS (...)) and subqueries are indented to show nesting clearly. Each subquery starts on its own line with deeper indentation than the surrounding query. This makes complex analytical queries with multiple CTEs much easier to read.

Can this tool help with slow queries?

Indirectly. Formatting does not change performance — but it makes it easier for you (and a DBA) to see JOIN structure, WHERE conditions, and subquery placement. Combined with EXPLAIN output, formatted SQL often reveals performance problems (missing indexes, unnecessary joins, expensive subqueries).

Does it handle stored procedures?

Yes — formatting extends to stored procedures with BEGIN ... END blocks, IF ... ELSE conditionals, and WHILE / FOR loops. Procedural syntax (T-SQL, PL/SQL) is dialect-specific, so select the right dialect for optimal formatting.

What about comments inside SQL?

Both single-line (--) and block (/* */) comments are preserved. Multi-line block comments may be indented to match surrounding code, but their content is not altered.

Can I format SQL from inside a string in my code?

Yes, but you need to extract the SQL first. Many IDEs can detect SQL in string literals and offer format actions. For ad-hoc formatting, copy the SQL content (without the surrounding quotes) into this tool, format it, then paste back.

Additional resources

Advertisement

Learn more

Explore more tools

200+ free tools that run in your browser.

Browse all tools →