SQL Formatter & Minifier

Standardize SQL query syntax across relational engines, or compress queries into single-line payloads for production code.

Dialect:
Preset:
SQL Input1 line • 532 B
1 statement detected
•
SELECT
  u.id,
  u.username,
  u.email,
  COUNT(o.id) AS total_orders,
  COALESCE(SUM(o.total_amount), 0) AS lifetime_spend,
  MAX(o.created_at) AS last_order_date
FROM
  users u
  LEFT JOIN orders o ON u.id = o.user_id
  AND o.status NOT IN ('cancelled', 'refunded')
WHERE
  u.active = 1
  AND u.created_at >= '2024-01-01'
  AND (
    u.country_code IN ('US', 'CA', 'GB')
    OR u.is_vip = TRUE
  )
GROUP BY
  u.id,
  u.username,
  u.email
HAVING
  COUNT(o.id) > 2
  AND COALESCE(SUM(o.total_amount), 0) >= 250.00
ORDER BY
  lifetime_spend DESC,
  u.username ASC
LIMIT
  50
OFFSET
  0;
586 B•32 lines•17ms
Need additional code transformations?

Operation Guide

Step 1

Load Query

Paste unformatted or minified SQL directly into the input editor, or drag and drop a local .sql file.

Step 2

Configure Rules

Select the engine dialect and set indentation width (2 spaces, 4 spaces, or tabs), keyword casing, and tabular alignment preferences.

Step 3

Inspect & Export

Verify clause modifications using the line-by-line Diff viewer, then copy the result to clipboard or download the processed query.

Transformation Examples

1. CTE, Subquery & JOIN Alignment

Raw Input (Single-Line CTE)

with regional_stats as (select department_id, avg(salary) as avg_sal from employees where status = 'active' group by department_id) select e.id, e.first_name, e.last_name, e.salary, r.avg_sal from employees e inner join regional_stats r on e.department_id = r.department_id where e.salary > r.avg_sal order by e.salary desc limit 20;

Formatted Output (Indented Clauses)

WITH regional_stats AS (
  SELECT
    department_id,
    avg(salary) AS avg_sal
  FROM
    employees
  WHERE
    status = 'active'
  GROUP BY
    department_id
)
SELECT
  e.id,
  e.first_name,
  e.last_name,
  e.salary,
  r.avg_sal
FROM
  employees e
  INNER JOIN regional_stats r ON e.department_id = r.department_id
WHERE
  e.salary > r.avg_sal
ORDER BY
  e.salary DESC
LIMIT
  20;

2. Comment Stripping with Optimizer Hint Retention

Input with Inline & Block Comments

-- Load active orders with index hint
/* Multi-line audit note: payment verification */
SELECT /*+ INDEX(orders idx_order_date) */
  id,
  customer_id,
  total_amount
FROM
  orders
WHERE
  status = 'completed'
  AND order_date >= '2024-01-01';

Minified Output (Hint Preserved)

SELECT /*+ INDEX(orders idx_order_date) */ id,customer_id,total_amount FROM orders WHERE status='completed' AND order_date>='2024-01-01';

3. DDL Schema Definition with Column Constraints

Raw DDL Statement

create table if not exists accounts (id bigint generated always as identity primary key, email varchar(255) not null unique, balance numeric(14,2) default 0.00 check (balance >= 0), created_at timestamp with time zone default current_timestamp);

Structured Schema Output

CREATE TABLE IF NOT EXISTS accounts (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email varchar(255) NOT NULL UNIQUE,
  balance numeric(14, 2) DEFAULT 0.00 CHECK (balance >= 0),
  created_at timestamp WITH time zone DEFAULT current_timestamp
);

Processing Rules & Configuration Reference

SettingAllowed ValuesMechanism & Safety Boundary
SQL DialectStandard ANSI / MySQL / PostgreSQL / SQLite / T-SQL / PL/SQL / MariaDB / Snowflake / BigQuery / ClickHouse / Redshift / DuckDBLoads database-specific keyword maps, identifier delimiters, and clause termination tokens.
Keyword CasingUPPERCASE / lowercase / PreserveNormalizes reserved SQL terms without modifying schema table names, aliases, or string constants.
Indentation Width2 spaces / 4 spaces / TabSets indent depth per nesting level across subqueries, CTEs, and parenthesized expressions.
Indent StyleStandard / Tabular Left / Tabular RightPositions root clauses flush-left or right-aligns primary keywords to form a vertical column margin.
Logical OperatorsBefore / AfterPlaces AND and OR conjunctions at the beginning of filter conditions or at the end of preceding lines.
Strip CommentsEnabled (Minify)Removes single-line (-- and #) and block (/* */) annotations while keeping literals inside quotes untouched.
Keep Optimizer HintsEnabled / DisabledDetects hint signatures (/*+ ... */) and preserves them in minified output to prevent plan degradation.

SQL Lexical Tokenization & AST Transformation Pipeline

SQL cannot be formatted reliably using regular expressions. SQL permits keywords inside string literals (e.g. 'SELECT status FROM logs'), escaped quotes ('' or \'), dialect-specific quote identifiers, and nested subquery parentheses. A production-grade SQL engine executes through four deterministic processing phases:

Phase 1

Lexical Stream

Breaks raw characters into typed tokens: keywords, operators, identifiers, literals, and comments. Token boundaries are sealed to prevent internal string mutation.

Phase 2

Paren & Scope Stacking

Tracks nesting depth across parentheses and Common Table Expressions, distinguishing subquery parenthesis blocks from scalar function arguments like COALESCE().

Phase 3

Clause Transformation

Applies clause line breaks (SELECT, FROM, WHERE), indents nested subtrees, or collapses whitespace runs depending on selected mode.

Phase 4

Serialization

Emits formatted text with configured line delimiters, or concatenates tokens into minimal single-line strings while preserving mandatory separator spaces.

Cross-Dialect Grammar & Identifier Matrix

Different database engines enforce distinct quotation standards, parameter placeholders, and query boundaries. The matrix below outlines how grammar variations are resolved:

Engine DialectIdentifier DelimiterParameter PlaceholdersSpecific Clauses & Features
Standard SQL (ANSI)"identifier"?FETCH FIRST n ROWS ONLY, standard window functions
MySQL & MariaDB`identifier`?, :paramLIMIT offset, count, ON DUPLICATE KEY UPDATE, # comments
PostgreSQL"identifier"$1, $2, ?RETURNING, ON CONFLICT DO UPDATE, dollar-quoted blocks ($$body$$)
SQLite`id`, "id", [id]?, ?1, :name, @name, $nameUPSERT syntax, AUTOINCREMENT, permissive type definitions
SQL Server (T-SQL)[identifier]@param, ?TOP (n), CROSS APPLY, OUTER APPLY, WITH (NOLOCK) table hints
Oracle PL/SQL"identifier":param, :1CONNECT BY, ROWNUM filtering, optimizer hints (/*+ ... */)
Snowflake & BigQuery`identifier` / "id"?, @paramQUALIFY clause, semi-structured FLATTEN / UNNEST, backtick tables
ClickHouse`identifier` / "id"? / {param:Type}PREWHERE, FINAL, ARRAY JOIN, ENGINE = MergeTree table settings
Amazon Redshift"identifier"?, $1DISTKEY, SORTKEY, VACUUM, UNLOAD / COPY data lake operations
DuckDB"identifier" / `id`?, $1, $nameCOLUMNS(*), EXCLUDE, REPLACE, direct Parquet / CSV querying

Minification Safety Invariants & Optimizer Hint Preservation

Compressing SQL queries requires adherence to strict lexical invariants. Unchecked character stripping causes execution syntax errors or performance degradation:

Token Collision Prevention

Whitespace between adjacent alphanumeric tokens (SELECT id FROM users) cannot be stripped without altering token identities into SELECTidFROMusers. Furthermore, consecutive arithmetic operators (like subtracting negative constants a - -1) must preserve separation so that the second minus sign is not misinterpreted as an inline comment prefix (--).

// Input: WHERE a - -1
// Safe Minification: WHERE a- -1 (Valid SQL)
// Unsafe Strip: WHERE a--1 (Triggers comment parse error)

Preserving Query Optimizer Hints

Database optimizers parse comments starting with /*+ (e.g. Oracle /*+ INDEX(t idx) */, MySQL /*+ MAX_EXECUTION_TIME(1000) */, or PostgreSQL pg_hint_plan) as operational directives rather than dead text. Indiscriminately deleting all comment blocks forces the planner to fall back to generic table scans.

// Comment with Optimizer Directive:
SELECT /*+ LEADING(e d) */ e.name FROM emp e ...
// Preserved in Output: Directive stays intact

Production Engineering Workflows

ORM Query Deobfuscation

Extract massive, single-line queries emitted by Hibernate, Prisma, TypeORM, or SQLAlchemy loggers. Formatting reveals nested joins, filter conditions, and missing indices during EXPLAIN ANALYZE investigations.

Database Migration Reviews

Standardize table schemas, index declarations, and foreign key constraints before committing migration scripts into Flyway, Liquibase, or Sqitch repositories to ensure clean Git diffs.

Payload & RPC Optimization

Minify raw SQL statements embedded inside microservice configuration files, JSON payloads, or RPC calls, trimming redundant whitespace bytes without altering relational semantics.

Slow Query Log Audits

Paste raw log entries collected from MySQL slow query logs, PostgreSQL pg_stat_statements, or AWS CloudWatch Insights to quickly diagnose query bottlenecks.

Frequently Asked Questions

How do I format complex SQL queries with nested subqueries and multiple JOINs?

Paste your SQL statement and select your preferred indentation width. The parser evaluates parenthesis depth and Common Table Expressions (CTEs), breaking root clauses (SELECT, FROM, WHERE, GROUP BY) onto new lines while cleanly indenting nested subqueries and JOIN ON conditions for clear visual hierarchy.

Will minifying SQL change query execution plans, results, or database speed?

No. Relational database engines (MySQL, PostgreSQL, Oracle, SQL Server) tokenize queries and discard redundant whitespace and non-hint comments before generating execution plans. Minified SQL produces identical results while reducing query payload size and bandwidth across network sockets and API calls.

How does dialect selection affect formatting across MySQL, PostgreSQL, SQLite, and SQL Server?

Each database engine follows distinct grammar specifications. Selecting the correct dialect ensures engine-specific quotation rules (MySQL backticks, T-SQL square brackets, PostgreSQL double quotes), string escaping, and specialized clauses (such as QUALIFY, RETURNING, or CROSS APPLY) are preserved and indented accurately.

Does the formatter support parameterized queries and prepared statement placeholders?

Yes. The formatter treats standard placeholders—including positional markers (?, $1, $2) and named parameters (:id, @user_id)—as atomic identifier tokens. Their syntax, prefix symbols, and exact numeric positions remain intact during both formatting and minification.

Why are database optimizer hints preserved when comments are removed during minification?

Database execution planners recognize structured comments beginning with /*+ (such as Oracle /*+ INDEX(...) */, MySQL /*+ MAX_EXECUTION_TIME(...) */, or PostgreSQL pg_hint_plan) as operational directives. Stripping these hints alongside regular comments would degrade query optimization and cause costly table scans.

What is the difference between standard indentation and tabular keyword alignment?

Standard indentation indents clause bodies relative to flush-left keywords. Tabular alignment right-justifies major keywords (SELECT, FROM, WHERE, ORDER BY) so that column lists, table references, and predicates align along a consistent vertical column margin, making complex queries easier to scan.

How does the Diff viewer highlight changes between raw and formatted SQL?

The Diff tab uses the Longest Common Subsequence (LCS) algorithm to compute line-level comparisons between original input and processed output. It highlights added indentation, normalized keyword casing, and stripped comments with color-coded diff markers before copying or downloading.