Free SQL formatter and validator. Automatically format SQL with proper indentation and capitalization. Check syntax errors instantly. Works with MySQL, PostgreSQL, SQL Server, Oracle.
Format and validate SQL queries with automatic indentation, keyword capitalization, and syntax error detection.
Ever inherited a database project where the SQL looks like someone typed it while blindfolded? You're not alone. Poorly formatted SQL is one of the most common sources of bugs and wasted time in database development.
This SQL formatter and validator helps you clean up messy queries automatically. Paste your SQL, and it instantly applies proper indentation, capitalizes keywords, and checks for syntax errors—all in your browser without sending data to any server. What typically takes 10-15 minutes of manual formatting happens in seconds.
In my experience working with database teams, the biggest time-saver isn't just the formatting—it's catching errors before they hit production. A misplaced parenthesis or unclosed quote can waste hours of debugging. This tool catches those issues immediately, before you execute anything against your database.
The interface is intentionally minimal—just paste and go:
Works on any device with a browser. The formatting happens entirely client-side, so your queries never leave your machine—important when working with production database structures or sensitive schemas.
All SQL keywords get capitalized automatically—SELECT, FROM, WHERE, JOIN, and so on. This follows the convention used by most database teams and makes keywords visually distinct from your table and column names. When you're scanning through a complex query, this visual separation helps you identify the query structure at a glance.
The formatter structures your SQL based on logical hierarchy rather than just adding random line breaks. Main clauses like SELECT and FROM start at the left margin. JOIN clauses indent under FROM to show they're part of the table selection. Subqueries get additional indentation levels, making nested logic clear.
Here's what happens in practice: when you have a query with multiple joins and subqueries, proper indentation lets you see the query structure without reading every word. You can instantly spot where one join ends and another begins, or where a subquery is being used in your SELECT list.
Line breaks appear where they help readability, not just everywhere. Each main clause gets its own line. Items in comma-separated lists (like column names in SELECT) each get their own line with proper indentation. Subqueries are visually separated. CASE statements break at WHEN, THEN, and ELSE for clarity.
The spacing follows the SQL Style Guide conventions used across the industry, which means your formatted SQL will look familiar to other developers.
The validator catches the errors that typically slip through when you're writing SQL quickly. It won't replace your database's query analyzer, but it catches common mistakes before you even run the query.
Unbalanced parentheses are surprisingly common in complex queries with nested subqueries. The validator counts opening and closing parentheses to flag mismatches immediately. I've seen production incidents caused by a single missing parenthesis in a 200-line query—this catches them early.
Unclosed string literals happen when you forget the closing quote on a string value. Your database will reject these immediately, but catching them here saves a round trip.
Clause ordering issues are flagged when clauses appear out of sequence. For example, if you put HAVING before GROUP BY, or WHERE after GROUP BY, the validator alerts you. This follows the SQL standard syntax rules defined in the ISO/IEC 9075 SQL standard.
JOIN clauses without ON conditions create accidental cross joins, returning way more rows than intended. A common scenario: you're adding a third or fourth table to a query and forget the ON clause. Without this check, you might not notice until you see thousands of duplicate rows in your results.
HAVING without GROUP BY is technically invalid SQL in most databases. The HAVING clause filters grouped results, so it requires a GROUP BY to work with. The validator catches this logical mismatch.
Incomplete WHERE conditions happen when you start typing a condition but don't finish it—like WHERE status = with no value. These are easy to miss when editing queries.
This validator focuses on syntax and structure, not database schema. It won't know if:
Think of it as a first-pass check before you send the query to your actual database.
The formatter applies consistent rules based on the SQL Style Guide conventions that most database teams follow.
Every SQL keyword becomes uppercase: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP. This includes clauses (FROM, WHERE, GROUP BY, HAVING, ORDER BY), join types (JOIN, INNER JOIN, LEFT JOIN), operators (AND, OR, NOT, IN, BETWEEN, LIKE), and common functions (COUNT, SUM, AVG, CASE, WHEN).
Why uppercase? It creates visual distinction between SQL's language elements and your database-specific names (tables, columns, aliases). When scanning a query, your eye immediately picks out the structure.
Main clauses like SELECT and FROM start at the left margin. JOIN clauses indent two spaces under FROM to show they're part of table selection. Subqueries indent another two spaces for each nesting level. This creates a visual hierarchy that matches the logical structure.
Comma-separated lists (column names in SELECT, for example) each get their own line with consistent indentation. When you have 15 columns in your SELECT list, this makes it easy to scan and find specific columns.
Conditions in WHERE clauses align vertically. When you have multiple AND or OR conditions, alignment makes the logic structure immediately obvious.
Before Formatting:
1select u.id, u.name, o.order_date from users u join orders o on u.id = o.user_id where o.status = "completed" group by u.id order by u.name;
2After Formatting:
1SELECT
2 u.id,
3 u.name,
4 o.order_date
5FROM users u
6 JOIN orders o ON u.id = o.user_id
7WHERE
8 o.status = "completed"
9GROUP BY
10 u.id
11ORDER BY
12 u.name;
13The validator checks structural integrity and basic logical consistency. Here's what it looks for:
Balanced parentheses: Opening and closing parentheses must match. Nested subqueries often have multiple levels of parentheses, and miscounting them is one of the most common SQL errors. The validator counts them for you.
Properly closed strings: Every opening quote (single or double) needs a closing quote. Sounds obvious, but when you're writing a complex query with multiple string literals, it's easy to miss one.
Correct clause order: SQL has specific ordering requirements. SELECT comes before FROM, which comes before WHERE, which comes before GROUP BY, which comes before HAVING, which comes before ORDER BY. Putting them out of sequence causes immediate syntax errors. The validator checks this ordering based on the SQL standard.
JOIN with ON condition: Every JOIN needs an ON or USING clause to specify how tables relate. Without it, you get a cross join—every row from one table paired with every row from the other. That's rarely what you want and usually indicates a missing ON clause.
Complete WHERE conditions: A WHERE clause needs complete predicates. WHERE status = with no value is incomplete and invalid. The validator flags these partial conditions.
HAVING requires GROUP BY: The HAVING clause filters grouped results, so it only makes sense when you have a GROUP BY. Using HAVING without GROUP BY is a logical error that most databases reject.
GROUP BY aggregation rules: When you use aggregate functions like COUNT() or SUM(), any non-aggregated columns in your SELECT list must appear in GROUP BY. This is a fundamental SQL requirement that the validator checks.
Here's SQL with multiple issues that the validator would flag:
1SELECT user_id, COUNT(*) FROM orders
2JOIN users
3WHERE status =
4GROUP BY
5HAVING count > 10;
6Problems detected:
JOIN users missing ON condition (will create cross join)WHERE status = incomplete (no comparison value)GROUP BY clause (no columns specified)HAVING count > 10 references undefined columnEver tried reviewing a 50-line SQL query that's written on a single line? It's brutal. Before submitting queries for code review, run them through the formatter. Your reviewers will thank you, and they'll actually be able to focus on logic instead of deciphering structure.
When reviewing pull requests with database changes, ask contributors to format their SQL first. It makes spotting logic errors much easier when the structure is consistent.
When you're troubleshooting a failing query in production, formatting it properly helps you see the structure clearly. I've debugged countless queries where the issue became obvious once the SQL was properly formatted—a missing join condition, an incorrect WHERE clause grouping, or a subquery in the wrong place.
Copy the query from your logs, paste it here, and you'll immediately see if there are structural issues.
ORMs (Object-Relational Mappers) like Hibernate, Entity Framework, or SQLAlchemy generate SQL automatically. Sometimes you need to see what query they're actually producing. The generated SQL is usually one long line with no formatting. This tool makes ORM-generated queries readable so you can understand and optimize them.
If you're learning SQL or teaching it, this formatter helps you understand proper query structure. When you paste a working query and see how it gets formatted, you learn the conventions. When you paste a broken query and see the validation errors, you understand why it doesn't work.
Different databases (PostgreSQL, MySQL, SQL Server) have slightly different SQL dialects. When migrating queries between systems, proper formatting helps you spot dialect-specific syntax that might need adjustment. The formatter follows standard SQL conventions that work across most major databases.
Tools like DataGrip, SQL Server Management Studio, or MySQL Workbench have built-in formatters. They're powerful and integrate directly with your database connections.
The tradeoff: they require installation and setup. DataGrip costs $199/year for individuals. SSMS is free but Windows-only. If you need quick formatting without installing anything, or you work across multiple database systems, a browser-based tool is more practical.
If you write SQL in VS Code or Sublime Text, extensions like SQL Beautify or SqlBeautifier bring formatting into your editor. This works well when you're actively writing queries and want immediate formatting as part of your workflow.
The limitation: extensions need configuration, and they're tied to your specific editor. When sharing SQL with teammates or posting queries in documentation, a standardized web formatter ensures everyone sees the same formatting.
Tools like sqlformat (Python) or sql-formatter-cli (Node.js) can be integrated into CI/CD pipelines to automatically format SQL in version control. This enforces consistency across a team.
Best used for automated workflows rather than ad-hoc formatting. If you're just cleaning up a few queries or learning SQL, command-line tools add unnecessary complexity.
SQL was developed at IBM in the 1970s, but formatting conventions emerged much later. Early SQL was functional but inconsistent—each developer formatted queries differently.
The turning point came in the 1990s when databases moved from single-developer projects to team-based development. Organizations started creating internal SQL style guides to maintain consistency. When you had five developers working on the same database, readable SQL became essential for collaboration.
The 2000s brought ORMs that generated SQL automatically. These tools produced working but ugly SQL—everything on one line, no indentation. This created demand for automated formatters that could make generated SQL human-readable.
Online SQL formatters appeared in the 2010s as web development matured. Instead of installing tools or configuring IDE plugins, developers could format SQL in a browser. This democratized access to proper formatting for everyone from beginners learning SQL to experienced developers cleaning up quick queries.
Today, SQL formatting is considered a baseline practice, similar to code formatting in other programming languages. The SQL Style Guide by Simon Holywell provides widely-adopted conventions, and tools like this implement those standards automatically.
Unformatted:
1select id, first_name, last_name, email from customers where status = 'active' order by last_name, first_name;
2Formatted:
1SELECT
2 id,
3 first_name,
4 last_name,
5 email
6FROM
7 customers
8WHERE
9 status = 'active'
10ORDER BY
11 last_name,
12 first_name;
13Unformatted:
1select c.id, c.name, o.order_date, o.total_amount from customers c left join orders o on c.id = o.customer_id where o.order_date >= '2023-01-01' and o.status != 'cancelled' order by o.order_date desc;
2Formatted:
1SELECT
2 c.id,
3 c.name,
4 o.order_date,
5 o.total_amount
6FROM
7 customers c
8 LEFT JOIN orders o ON c.id = o.customer_id
9WHERE
10 o.order_date >= '2023-01-01'
11 AND o.status != 'cancelled'
12ORDER BY
13 o.order_date DESC;
14Unformatted:
1select d.department_name, (select count(*) from employees e where e.department_id = d.id) as employee_count, (select avg(salary) from employees e where e.department_id = d.id) as avg_salary from departments d where d.active = true having employee_count > 0 order by avg_salary desc;
2Formatted:
1SELECT
2 d.department_name,
3 (
4 SELECT
5 COUNT(*)
6 FROM
7 employees e
8 WHERE
9 e.department_id = d.id
10 ) AS employee_count,
11 (
12 SELECT
13 AVG(salary)
14 FROM
15 employees e
16 WHERE
17 e.department_id = d.id
18 ) AS avg_salary
19FROM
20 departments d
21WHERE
22 d.active = TRUE
23HAVING
24 employee_count > 0
25ORDER BY
26 avg_salary DESC;
27Here are examples of how to implement SQL formatting in various programming languages:
1// JavaScript SQL formatting example using sql-formatter library
2const sqlFormatter = require('sql-formatter');
3
4function formatSQL(sql) {
5 return sqlFormatter.format(sql, {
6 language: 'sql',
7 uppercase: true,
8 linesBetweenQueries: 2,
9 indentStyle: 'standard'
10 });
11}
12
13const rawSQL = "select id, name from users where status='active'";
14const formattedSQL = formatSQL(rawSQL);
15console.log(formattedSQL);
161# Python SQL formatting example using sqlparse
2import sqlparse
3
4def format_sql(sql):
5 return sqlparse.format(
6 sql,
7 reindent=True,
8 keyword_case='upper',
9 identifier_case='lower',
10 indent_width=2
11 )
12
13raw_sql = "select id, name from users where status='active'"
14formatted_sql = format_sql(raw_sql)
15print(formatted_sql)
161// Java SQL formatting example using JSqlParser
2import net.sf.jsqlparser.parser.CCJSqlParserUtil;
3import net.sf.jsqlparser.statement.Statement;
4
5public class SQLFormatter {
6 public static String formatSQL(String sql) throws Exception {
7 Statement statement = CCJSqlParserUtil.parse(sql);
8 return statement.toString()
9 .replaceAll("(?i)SELECT", "\nSELECT")
10 .replaceAll("(?i)FROM", "\nFROM")
11 .replaceAll("(?i)WHERE", "\nWHERE")
12 .replaceAll("(?i)ORDER BY", "\nORDER BY");
13 }
14
15 public static void main(String[] args) throws Exception {
16 String rawSQL = "select id, name from users where status='active'";
17 String formattedSQL = formatSQL(rawSQL);
18 System.out.println(formattedSQL);
19 }
20}
211<?php
2// PHP SQL formatting example
3function formatSQL($sql) {
4 // Replace keywords with uppercase versions
5 $keywords = ['SELECT', 'FROM', 'WHERE', 'JOIN', 'LEFT JOIN', 'RIGHT JOIN',
6 'INNER JOIN', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT'];
7
8 $formattedSQL = $sql;
9 foreach ($keywords as $keyword) {
10 $formattedSQL = preg_replace('/\b' . preg_quote($keyword, '/') . '\b/i', "\n$keyword", $formattedSQL);
11 }
12
13 // Add indentation
14 $lines = explode("\n", $formattedSQL);
15 $result = '';
16 $indentLevel = 0;
17
18 foreach ($lines as $line) {
19 $trimmedLine = trim($line);
20 if (!empty($trimmedLine)) {
21 $result .= str_repeat(" ", $indentLevel) . $trimmedLine . "\n";
22 }
23 }
24
25 return $result;
26}
27
28$rawSQL = "select id, name from users where status='active'";
29$formattedSQL = formatSQL($rawSQL);
30echo $formattedSQL;
31?>
32Yes, it handles standard SQL syntax that's common across major databases—PostgreSQL, MySQL, SQL Server (T-SQL), Oracle, SQLite, and MariaDB. The formatter focuses on core SQL that works everywhere: SELECT, JOIN, WHERE, GROUP BY, and so on.
Database-specific features might not format perfectly. For example, PostgreSQL's array syntax or SQL Server's proprietary functions might not get special formatting treatment, but they won't break the formatter either. The query will still be more readable than it was.
No. Everything happens in your browser. Paste your SQL, and it gets formatted locally without any network requests. Your queries never leave your machine.
This matters when you're working with production database schemas or proprietary business logic. There's no risk of sensitive information being logged or stored on someone else's server.
Not even close. It catches structural and syntax issues—missing parentheses, unclosed quotes, clauses in the wrong order. That's it.
It won't know if your table names are wrong, your data types are incompatible, or your query will take 10 minutes to run. For that, you need your actual database. Think of this validator as spell-check for SQL, not a full query analyzer.
Databases don't care about formatting—they parse the query regardless. But humans care. When you need to debug a failing query, modify an existing one, or review someone else's SQL, proper formatting makes the difference between understanding it in 30 seconds versus 30 minutes.
Formatted SQL also helps you spot logic errors. When the structure is clear, you can see if you've joined tables incorrectly or put conditions in the wrong place.
Not currently. The formatter uses standard conventions: uppercase keywords, two-space indentation, clauses on separate lines. These follow the SQL Style Guide that most teams use.
If you need custom formatting (different indentation width, lowercase keywords), you'll need a configurable command-line tool like sqlformat or an IDE with formatting settings.
It'll format large queries, though very complex stored procedures (1000+ lines) might take a few seconds to process. The formatter handles the SQL you paste, regardless of length.
For massive stored procedures, you might want to break them into smaller chunks or use a database-specific IDE that's optimized for large files.
No. Formatting only adds whitespace and changes capitalization. Your database ignores both. The formatted query returns exactly the same results and runs with the same performance as the unformatted version.
The only exception: if the validator finds actual syntax errors (missing parentheses, etc.), fixing those will change behavior—but only from "doesn't run" to "runs correctly."
The formatter follows SQL-92 conventions with extensions for common features in SQL:1999 and later standards. This covers the SQL that most developers write daily—SELECT queries, joins, subqueries, CASE statements, window functions.
Very new SQL features from SQL:2016 or SQL:2019 might not be recognized, but they won't break the formatter. You'll just get basic formatting instead of specialized handling.
For basic queries, yes. For procedural code (PL/SQL blocks, T-SQL stored procedures with control flow), the formatting will be limited. The tool focuses on SELECT, INSERT, UPDATE, DELETE statements and their clauses.
If you're working heavily with database-specific procedural code, your database's native IDE (SQL Developer for Oracle, SSMS for SQL Server) will provide better formatting that understands the full syntax.
Readable SQL makes debugging faster, code reviews easier, and collaboration smoother. Paste your query above to see it formatted according to industry-standard conventions—no installation, no configuration, no data leaving your browser.
Discover more tools that might be useful for your workflow