SQL Formatter
The SQL Formatter is a free browser-based tool that formats and beautifies SQL queries without sending data to any server. It uses the sql-formatter JavaScript library, supports seven SQL dialects (Standard SQL, MySQL, PostgreSQL, SQLite, PL/SQL, T-SQL, BigQuery), enforces uppercase keywords, provides adjustable indentation, and reports syntax errors in the status bar.
SQL Formatter
How it works
Last updated: November 2026SQL (Structured Query Language) is the standard language for querying and manipulating relational databases. Every relational database — MySQL, PostgreSQL, SQLite, Oracle, SQL Server, BigQuery — uses SQL as its primary interface, though each dialect adds proprietary extensions and syntax variations.
This tool uses the sql-formatter JavaScript library to parse and reformat SQL entirely in your browser. No data is ever sent to a server. The library supports seven SQL dialects and enforces uppercase keywords — the widely adopted style that distinguishes SQL structure from data identifiers.
- Beautify — parses your SQL and re-serializes it with consistent indentation and uppercase keywords. Rewrites the input box so you always see clean SQL.
- Minify — collapses SQL to a single line for embedding in application code strings. Output only — input is unchanged.
- Dialect — select the target database to get correct identifier quoting (backticks for MySQL, double quotes for PostgreSQL) and dialect-specific keyword handling.
- Validate — the formatter catches syntax errors (mismatched parentheses, unclosed strings, unknown tokens) and reports them in the status bar.
SQL Quick Reference
| Clause | Purpose | Example |
|---|---|---|
| SELECT | Choose which columns to return | SELECT id, name, email |
| FROM | Specify the source table(s) | FROM users |
| WHERE | Filter rows before aggregation | WHERE status = 'active' |
| JOIN | Combine rows from multiple tables | INNER JOIN orders ON users.id = orders.user_id |
| LEFT JOIN | All left rows + matching right rows | LEFT JOIN orders ON users.id = orders.user_id |
| RIGHT JOIN | All right rows + matching left rows | RIGHT JOIN orders ON users.id = orders.user_id |
| GROUP BY | Aggregate rows by column values | GROUP BY department |
| HAVING | Filter groups after aggregation | HAVING COUNT(*) > 5 |
| ORDER BY | Sort result rows | ORDER BY created_at DESC |
| LIMIT / OFFSET | Paginate results (MySQL/PostgreSQL) | LIMIT 20 OFFSET 40 |
| INSERT | Add new rows to a table | INSERT INTO users (name, email) VALUES ('Alice', '[email protected]') |
| UPDATE | Modify existing rows | UPDATE users SET status = 'active' WHERE id = 1 |
| DELETE | Remove rows from a table | DELETE FROM users WHERE id = 1 |
SQL Dialect Differences
While ANSI SQL defines a common core, each database extends the language with proprietary syntax. Selecting the right dialect in the formatter ensures correct identifier quoting and keyword formatting for your target database.
| Feature | MySQL | PostgreSQL | T-SQL (SQL Server) | PL/SQL (Oracle) |
|---|---|---|---|---|
| Identifier quoting | `table` | "table" | [table] | "table" |
| Top N rows | LIMIT 10 | LIMIT 10 | TOP 10 / FETCH NEXT 10 | FETCH FIRST 10 ROWS |
| String concat | CONCAT(a, b) | a || b | a + b | a || b |
| Auto-increment | AUTO_INCREMENT | SERIAL / GENERATED | IDENTITY(1,1) | GENERATED AS IDENTITY |
| JSON support | JSON type, -> operator | JSON / JSONB, -> ->> | JSON_VALUE, OPENJSON | JSON_VALUE (12c+) |
| Upsert syntax | INSERT ... ON DUPLICATE KEY | INSERT ... ON CONFLICT | MERGE | MERGE |
Tips & Tricks
Dialect selector changes identifier quoting
Switch to MySQL to format backtick-quoted identifiers (`users`); switch to PostgreSQL for double-quote identifiers ("users"). The wrong dialect may reformat quoting incorrectly.
Minify before embedding in application code
Multi-line SQL in string literals makes code hard to read. Use Minify to collapse to a single line for embedding in Python, JavaScript, or Go source files, then add a comment pointing to the formatted version.
Uppercase keywords aid code reviews
When all SQL keywords are uppercase, reviewers can instantly distinguish structure (WHERE, JOIN) from schema identifiers (users, orders). Consistent formatting reduces cognitive load in pull requests.
Use CTEs to break up complex queries
A WITH clause (CTE) names a subquery so you can reference it multiple times. The formatter indents CTEs clearly, making it much easier to follow multi-step data transformations than deeply nested subqueries.
T-SQL uses TOP instead of LIMIT
If you switch between MySQL/PostgreSQL and SQL Server, remember that SELECT TOP 10 * goes before the column list in T-SQL, while LIMIT 10 goes at the end in MySQL/PostgreSQL. Select the T-SQL dialect to format SQL Server queries correctly.
Always add WHERE before UPDATE or DELETE
UPDATE users SET active = 0 without a WHERE clause updates every row. Beautifying your query before running it helps catch missing WHERE clauses before they cause data loss.
Code Examples
Node.js — sql-formatter
import { format } from 'sql-formatter';
const formatted = format(
'select id,name from users where active=1',
{
language: 'mysql',
tabWidth: 2,
keywordCase: 'upper',
linesBetweenQueries: 1,
}
);
console.log(formatted);
// SELECT
// id,
// name
// FROM
// users
// WHERE
// active = 1 Python — sqlparse
import sqlparse
sql = 'select id,name from users where active=1'
formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
print(formatted)
# SELECT id,
# name
# FROM users
# WHERE active=1
# For more control use sqlparse.parse()
parsed = sqlparse.parse(sql)[0]
for token in parsed.tokens:
print(token.ttype, repr(token)) CLI — pgFormatter & sqlfluff
# pgFormatter — format PostgreSQL / SQL files in place pg_format --inplace query.sql # Format and write to stdout pg_format query.sql # Use sqlfluff to lint and fix SQL pip install sqlfluff sqlfluff fix --dialect postgres query.sql # Format SQL in a pipeline (Node.js npx) echo "select id from users" | npx sql-formatter-cli --language mysql
Frequently Asked Questions
- What is SQL?
- SQL (Structured Query Language) is the standard language for querying and manipulating relational databases. It was first developed at IBM in the 1970s by Edgar Codd and Donald Chamberlin, standardized as ANSI SQL in 1986, and is now the universal interface to relational databases including MySQL, PostgreSQL, SQLite, Oracle, SQL Server, and BigQuery. SQL consists of four sublanguages: DML (Data Manipulation Language: SELECT, INSERT, UPDATE, DELETE), DDL (Data Definition Language: CREATE, ALTER, DROP, TRUNCATE), DCL (Data Control Language: GRANT, REVOKE), and TCL (Transaction Control Language: COMMIT, ROLLBACK, SAVEPOINT). Despite the existence of NoSQL databases (MongoDB, DynamoDB, Redis), SQL remains the dominant data query language — PostgreSQL and MySQL consistently rank among the top 2-3 most used databases worldwide. Modern SQL databases also support JSON columns, full-text search, and window functions.
- What SQL dialects are supported?
- The formatter supports Standard SQL, MySQL, PostgreSQL, SQLite, PL/SQL (Oracle), T-SQL (SQL Server), and BigQuery. Selecting the correct dialect matters because each database uses different identifier quoting (MySQL uses backticks, PostgreSQL and SQLite use double quotes, T-SQL uses square brackets), different pagination syntax (MySQL/PostgreSQL use LIMIT/OFFSET, SQL Server uses TOP or OFFSET...FETCH NEXT), and dialect-specific functions and keywords. For example, string concatenation uses
CONCAT()in MySQL,||in PostgreSQL and SQLite, and+in T-SQL. Date arithmetic also differs significantly — always select the correct dialect to get idiomatic formatting for your target database. - Why does the formatter uppercase SQL keywords?
- SQL keywords are case-insensitive in all major databases, but writing keywords in uppercase (SELECT, FROM, WHERE) and identifiers in lowercase (users, id, name) is the most widely adopted style in professional codebases, SQL style guides (such as Simon Holywell's SQL Style Guide), and database documentation. Uppercase keywords improve scannability — you can instantly distinguish language structure from data identifiers at a glance, which matters when reading complex multi-join queries. This convention is enforced by popular linters such as SQLFluff (which supports auto-fix) and pgFormatter. Some teams prefer all-lowercase SQL for a modern aesthetic, but mixed-case — where only the first letter of a keyword is capitalized — should be avoided as it is the hardest to read and not standardized anywhere.
- Is my SQL sent to a server?
- No. All formatting, minification, and validation runs entirely in your browser using JavaScript. Your SQL queries never leave your machine and no account or sign-up is required. This makes the tool safe to use with sensitive production queries containing real table names, column names with PII semantics, or WHERE clauses that reveal your data schema structure. The sql-formatter library runs entirely client-side — there are no network requests made when you click Beautify or Minify. Many developers working with financial, healthcare, or government data have strict policies against pasting production SQL into external tools; this formatter is safe to use in those environments. You can verify by checking the browser's Network tab while formatting a query.
- What is the difference between WHERE and HAVING?
- WHERE filters rows before aggregation; HAVING filters groups after aggregation. WHERE cannot reference aggregate functions (COUNT, SUM, AVG, MAX, MIN) because those are computed after grouping — using an aggregate in WHERE causes a syntax error in all major databases. HAVING is always used with GROUP BY. A practical example:
SELECT dept, COUNT(*) FROM employees WHERE salary > 50000 GROUP BY dept HAVING COUNT(*) > 5— the WHERE clause removes low-salary employees before grouping happens, then HAVING removes departments with five or fewer remaining employees. This distinction matters for performance: WHERE reduces the number of rows that enter the grouping operation, which is significantly more efficient than filtering on aggregates. When possible, push as much filtering as possible into WHERE rather than HAVING. - What is the difference between INNER JOIN and LEFT JOIN?
- INNER JOIN returns only rows where the join condition matches in both tables — unmatched rows are excluded from the result entirely. LEFT JOIN (also LEFT OUTER JOIN) returns all rows from the left table plus matching rows from the right table; if no match exists, the right-table columns are NULL in that row. Use INNER JOIN when you only want records with data in both tables — for example, orders with their associated products. Use LEFT JOIN when you want all records from the primary table regardless of whether a related record exists — for example, all users, including those who have never placed an order. A common mistake is adding a WHERE clause on a right-table column in a LEFT JOIN (e.g. WHERE orders.id IS NOT NULL), which silently converts it to an INNER JOIN. RIGHT JOIN is equivalent to a LEFT JOIN with the tables swapped and is less commonly used.
- What does SELECT * mean and should I avoid it?
- SELECT * retrieves all columns from the table. It is convenient for ad hoc queries and debugging but should be avoided in production code for three specific reasons: it fetches columns you may not need (increasing I/O, network transfer, and memory usage on the application server), it breaks when columns are added or reordered — especially in INSERT INTO t2 SELECT * FROM t1 statements where column order matters — and it prevents the optimizer from using covering indexes (an index that satisfies the entire query without touching the base table). In ORM frameworks like Hibernate and SQLAlchemy, avoid eager-loading all columns on large tables. Always name the specific columns your query actually uses. For debugging, SELECT * is perfectly fine in development environments where query plan overhead is not a concern.
- How do I write comments in SQL?
- SQL supports two comment styles. Single-line comments start with
--(double-dash) and extend to the end of the line:SELECT id -- primary key. Block comments use/* ... */and can span multiple lines, useful for documenting complex queries or temporarily disabling sections of a query. Both styles are preserved by the formatter when it re-serializes SQL. MySQL also supports#as a single-line comment delimiter, but this is non-standard and not recognized by PostgreSQL, SQL Server, or Oracle — avoid it in queries that may run on multiple database backends. In database migration tools such as Flyway and Liquibase, SQL comments in migration files are often retained in the migration log for documentation purposes, so writing clear comments pays dividends during future audits. - What is SQL injection and how do I prevent it?
- SQL injection is an attack where malicious SQL is inserted through user-supplied input to manipulate a database query. If a login query is built by string concatenation, an attacker can enter a value like
' OR '1'='1to bypass authentication entirely, or'; DROP TABLE users; --to destroy data. SQL injection is consistently ranked in the OWASP Top 10 most critical web security risks. Prevention: always use parameterized queries (prepared statements) which pass user input as typed parameters rather than interpolated strings — in Python:cursor.execute('SELECT * FROM users WHERE id = %s', (user_id,)); in Node.js:db.query('SELECT * FROM users WHERE id = ?', [userId]). ORM frameworks like SQLAlchemy, Prisma, and Hibernate use parameterized queries by default. Never build SQL by concatenating user input, even after sanitization. - What is a JOIN in SQL?
- A JOIN combines rows from two or more tables based on a related column condition specified in the ON clause. The main types are: INNER JOIN (only rows where the condition matches in both tables), LEFT JOIN (all left rows plus matching right rows, with NULLs for non-matches on the right), RIGHT JOIN (all right rows plus matching left rows), FULL OUTER JOIN (all rows from both tables, NULLs where there is no match on either side), and CROSS JOIN (the Cartesian product of all row combinations, rarely used intentionally). Joins are fundamental to relational databases because the relational model stores data in normalized separate tables to eliminate redundancy, and joins reconstitute the data at query time. A table with an index on its join column is essential for performance — without an index, a JOIN results in a full table scan, which degrades exponentially as table size increases.
- Does the formatter validate my SQL?
- Yes. The formatter uses the sql-formatter library to parse your SQL before reformatting it. If the SQL cannot be parsed — syntax errors, mismatched parentheses, unclosed string literals, unrecognized dialect-specific keywords — it reports an error in the status bar with context about where parsing failed. Note that sql-formatter performs syntactic validation only; it cannot verify that table names, column names, or functions exist in your database schema — that is semantic validation, which requires a live database connection. For deeper SQL linting including naming conventions, anti-patterns (SELECT *), and style rules, use SQLFluff (pip install sqlfluff) which supports all major dialects and integrates with pre-commit hooks and CI pipelines. SQLFluff can also auto-fix many style issues with the fix command.
- What is the difference between TRUNCATE and DELETE?
- DELETE removes rows one at a time, logs each deletion in the transaction log, supports a WHERE clause for selective removal, can be rolled back in a transaction, fires DELETE triggers, and updates auto-increment counters only implicitly. TRUNCATE removes all rows by deallocating data pages in bulk — it is significantly faster for large tables (seconds vs. minutes), cannot be filtered with WHERE, does not fire row-level triggers, and in MySQL cannot be rolled back (though PostgreSQL and SQL Server do support TRUNCATE inside a transaction). Additionally, TRUNCATE resets identity/auto-increment counters to their seed value in most databases, while DELETE does not. Use DELETE when you need a WHERE clause, need rollback safety, or need triggers to fire. Use TRUNCATE to quickly and efficiently empty an entire table in a development or testing scenario. Never TRUNCATE a production table without a verified recent backup.
- What is a subquery in SQL?
- A subquery (also called an inner query or nested query) is a SELECT statement embedded inside another SQL statement. Subqueries can appear in the SELECT list (scalar subquery returning one value), the FROM clause (derived table or inline view), the WHERE clause with IN, EXISTS, or comparison operators, or the HAVING clause. Example:
SELECT name FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100). A correlated subquery references a column from the outer query and is re-evaluated for every row of the outer query — which can be slow for large tables. CTEs (Common Table Expressions, written with the WITH clause) are often more readable than deeply nested subqueries and allow you to reference the same subquery multiple times. CTEs are supported in PostgreSQL 8.4+, SQL Server 2005+, MySQL 8.0+, and SQLite 3.35+.
Related Tools
Other free developer tools available on DevFormatter.
JSON Formatter
Format, validate, and minify JSON. Sort keys, find duplicates, and explore with Tree view.
YAML Formatter
Format, validate, and convert YAML. Detects YAML 1.1 coercion risks and expands anchors.
XML Formatter
Format, validate, and convert XML. Highlights errors with line and column positions.
CSS Formatter
Format and beautify CSS stylesheets with consistent indentation and property ordering.