SQL Formatter

-- Formatted SQL --



How to Use the SQL Formatter

1

Paste your SQL query

Paste your SQL query.

2

Choose indentation style

Choose indentation style.

3

Click Format

Click Format.

4

Copy the formatted SQL

Copy the formatted SQL.

SQL Formatter — Beautify and Structure Your SQL Queries Online

Every database developer has opened a file and found a query that looks like this: SELECT u.id,u.name,o.total,o.created_at FROM users u INNER JOIN orders o ON u.id=o.user_id WHERE o.total>100 AND o.created_at>'2024-01-01' ORDER BY o.total DESC LIMIT 50. It runs. It returns the right rows. But it's genuinely painful to read, review, or modify — and anyone touching it next will spend five minutes just parsing its structure before making a single change. SQL formatting fixes this. It takes your query and rebuilds it with consistent keyword casing, logical line breaks at clause boundaries, and indentation that makes nested structures immediately visible. The query executes identically. It just becomes something you can reason about.

This free online formatter handles MySQL, PostgreSQL, SQL Server, SQLite, and Oracle syntax. Paste a single SELECT, a multi-join analytical query, a CREATE TABLE statement, a stored procedure — and get back properly structured, readable code in seconds. All processing runs in your browser; nothing is sent to any server.

What Formatting Actually Changes (and What It Doesn't)

SQL parsers are completely whitespace-agnostic. The database engine sees the same logical query whether it's written on a single 400-character line or spread across thirty lines with careful indentation. Formatting doesn't touch the logic, doesn't change the query plan, doesn't affect execution time, and doesn't influence which indexes are used. It changes only the visual structure of the source text.

What a formatter does: moves each major clause (SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT) onto its own line. Breaks long column lists so each column appears on a separate line. Indents JOIN conditions below their JOIN keyword. Nests subqueries visually beneath their parent. Aligns WHERE clause predicates for quick scanning. Delineates CTEs with clear block structure. Normalizes keyword casing to a consistent style (uppercase is conventional).

The query that was a wall of text becomes a readable document you can scan top-to-bottom and understand the query's strategy without executing it. And because the output is semantically identical to the input, you can format and re-format freely with zero risk of breaking anything.

When Formatting Makes the Real Difference

A three-line SELECT with a WHERE clause is readable enough without help. The real payoff comes at complexity:

Multi-table JOINs: A query joining six tables with mixed INNER, LEFT, and CROSS JOINs, each with its own ON conditions — that's unreadable as a single line. Formatted, each JOIN occupies its own line with ON conditions indented beneath it. You immediately see the join order, which tables are inner-joined (required matches) vs. left-joined (optional), and what keys connect them — all without tracing through the raw text.

Common Table Expressions: CTEs are powerful but visually dense. A query with four CTEs followed by a main SELECT that joins all four together becomes genuinely hard to follow in raw form. A formatter places each CTE in its own labeled block, making the data flow explicit — this CTE produces users, this one produces their orders, this one calculates the aggregate, and the final SELECT brings them together.

Correlated subqueries: When an inner SELECT references columns from the outer SELECT, the relationship between them is critical to understanding the query's correctness and performance. Without indentation, that relationship is buried in the text. With proper formatting, the subquery is visually nested inside the outer query, and the column references that cross the boundary become obvious.

ORM-generated SQL: Eloquent, Hibernate, SQLAlchemy, ActiveRecord, Prisma — they all generate SQL programmatically, and the output is always a single unformatted line. When you need to debug a slow query or understand what an ORM is actually doing under the hood, formatting the generated SQL is the fastest way to see its structure clearly.

SQL Formatting Conventions Worth Adopting

SQL lacks an official style guide — it's not Python with PEP 8 — but there are conventions that most professional teams follow. Consistency across a codebase matters more than any single stylistic choice.

Keyword casing: The longstanding convention is uppercase for SQL keywords (SELECT, FROM, WHERE, JOIN) and lowercase for identifiers (table names, column names, aliases). This creates a clear visual boundary between the language and your schema. Some PostgreSQL-heavy teams use all-lowercase for everything. Either approach is fine, but mixing within a single query makes it harder to scan. Pick one and enforce it.

Indentation depth: Subqueries and CTEs should be indented relative to their enclosing context — typically by 2 or 4 spaces. Column lists after SELECT are often aligned or each gets its own line. The exact indent size matters less than applying the same rule to every query in the project.

Meaningful aliases: Table aliases should describe what the table represents — cust for customers, ord for orders — not arbitrary single letters. A well-formatted query immediately highlights poor aliasing choices because the indented structure makes it obvious when an alias like x appears in a JOIN but is referenced ten lines later in a WHERE clause with no context for what x actually is.

Formatting and Code Review — Why It Matters More Than You Think

If your application stores SQL in migration files, model files, or dedicated query files, those queries go through code review like any other code. And formatting has an outsized impact on review quality.

Consider a change to an unformatted single-line query: the diff shows a modified 300-character line. The reviewer has to mentally diff the two versions — was a condition removed? Was a JOIN type changed? Was a column added to the SELECT? The change is buried in the line. The same change in a formatted query shows up as an addition or removal of a specific line — a new JOIN condition, a changed WHERE predicate, a modified column. The intent is immediately visible and the review is faster and more reliable.

Teams using Flyway, Liquibase, or Laravel's built-in migrations benefit even more. A well-formatted CREATE TABLE statement from a year ago is a readable document you can audit in seconds. An unformatted one-liner requires mental reconstruction every time someone reviews the migration history. Consistently formatted SQL in version control is a long-term investment in maintainability.

When Not to Format — Minified SQL Has Its Place

Formatting isn't universally desirable. In production application code where SQL is embedded as a string in a function call, a compact one-liner avoids awkward multi-line string handling in languages that don't support heredocs cleanly. In log files and monitoring tools, minified queries are easier to grep for patterns. In performance profiling, a single-line query is easier to paste into a monitoring dashboard without extra whitespace. The key is knowing when readability (formatted) matters more than compactness (minified) — and having a formatter lets you move between the two freely as context demands.

Frequently Asked Questions About SQL Formatting

No. SQL parsers treat whitespace — spaces, tabs, newlines — as token separators and discard everything else. A query written on a single line and the same query with careful formatting and indentation produce identical results, identical execution plans, and identical performance. The formatter changes only the source text's visual structure. Nothing else.
Uppercase keywords (SELECT, FROM, WHERE, JOIN) are the traditional convention and remain the most widely adopted style in professional SQL development. It creates a clear visual separation between language keywords and your schema's identifiers. PostgreSQL communities sometimes prefer all-lowercase for everything, and that's equally valid — the important thing is consistency within a codebase. Mixing styles makes queries harder to scan. Pick a convention and apply it everywhere.
Yes. The core SQL clause structure — SELECT, FROM, WHERE, GROUP BY, JOIN, ORDER BY, HAVING, LIMIT/TOP — is consistent across MySQL, PostgreSQL, SQL Server, SQLite, and Oracle. The formatter handles this shared structure correctly for all of them. Database-specific extensions (PostgreSQL's :: type casting, SQL Server's TOP instead of LIMIT, Oracle's CONNECT BY) may receive less dialect-aware formatting, but the overall structure is still reformatted correctly.
Yes. The formatter handles multi-statement SQL including BEGIN...END blocks, IF...THEN conditionals, loops, cursors, stored procedure declarations, and trigger definitions. Complex procedures with multiple CTEs, nested logic, and exception handling become significantly more readable after formatting. This is one of the biggest practical wins — a stored procedure written as a single unformatted block is nearly impossible to debug, and formatting it is the first step toward understanding what it does.
For inline queries embedded in application code, use multiline string literals with each major clause on its own line — PHP's heredoc syntax, Python's triple-quoted strings, and JavaScript template literals all support this cleanly. For complex or reusable queries, store them in separate .sql files, in named query definitions in your ORM, or in migration files managed by Flyway, Liquibase, or Laravel's built-in migration system. Keeping complex SQL in its own file makes it versionable, reviewable, and testable independently from application logic.
Formatting doesn't change the query plan or execution behavior — the optimizer sees the same logical statement regardless of whitespace. The indirect benefit is significant though: formatted, readable SQL makes it much easier to spot structural problems that affect performance. An unnecessary subquery that could be a JOIN, a missing index condition buried in a long WHERE clause, a correlated subquery that would be better rewritten as a CTE — these issues are visible when the query is structured and hidden when it's a wall of text. Readable SQL is auditable SQL.
ORMs log their generated SQL as a single unformatted line by default — it's how the logging libraries serialize the query string. To analyze or debug it, copy the logged query, paste it into a formatter, and you'll immediately see the JOIN structure, WHERE conditions, and subqueries laid out clearly. This is the single most common real-world use case for online SQL formatters: developers debugging slow ORM-generated queries and needing to understand what's actually being executed.
Yes. Several approaches work: VS Code's SQL Formatter extension can be configured with a team-agreed style and set to format-on-save. JetBrains DataGrip has built-in formatting with exportable style configurations that the whole team shares. For automated enforcement, the sql-formatter npm package can run as a pre-commit hook or CI check — it reformats SQL files in committed code and flags files that don't match the agreed style. DBeaver supports format-on-shortcut. The point is the same as any other code style: automated enforcement eliminates style debates in code review.