SQL Formatter

Format and beautify SQL queries for better readability

Tool Overview

The SQL Formatter helps you format SQL queries into a readable structure with proper indentation and line breaks. It supports various SQL dialects and makes complex queries easier to understand.

Go to Tool

How It Works

The SQL Formatter uses lexical analysis and syntax formatting algorithms to structure SQL queries for improved readability.

Processing Flow

  1. Lexical Analysis: Breaks SQL into tokens:
    • Keywords (SELECT, FROM, WHERE, etc.)
    • Identifiers (table names, column names)
    • Strings, numbers, operators
    • Comments (--, /* */)
  2. Formatting Rules: Applies formatting based on SQL syntax:
    • SELECT clause: Each field on new line
    • FROM/WHERE/JOIN/ORDER BY keywords on new lines
    • Appropriate indentation levels for nested structures
  3. Case Conversion: Supports UPPER/LOWER/CamelCase for keywords.
  4. Syntax Highlighting: Applies colors to different token types.

Supported SQL Dialects

  • MySQL: Full support for MySQL-specific syntax
  • PostgreSQL: Support for PostgreSQL features
  • SQL Server: Compatibility with T-SQL

Complex Query Handling

-- Nested structures are properly indented SELECT u.name, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) as order_count FROM users u WHERE u.created_at > '2024-01-01' -- Multiple JOIN operations SELECT u.name, p.product_name FROM users u INNER JOIN orders o ON u.id = o.user_id INNER JOIN products p ON o.product_id = p.id

Comments are preserved during formatting, maintaining their relative position in the query. The formatter maintains proper indentation for nested structures and adds consistent spacing around operators.

Features

  • Support for major SQL dialects (MySQL, PostgreSQL, SQL Server)
  • Indentation options (2, 4 spaces, tabs)
  • Uppercase/lowercase keyword conversion
  • Syntax highlighting
  • Multi-statement support

Usage Examples

Example 1: SELECT Query

Input:

SELECT id,name,email FROM users WHERE age > 18 ORDER BY name LIMIT 10

Output:

SELECT id, name, email FROM users WHERE age > 18 ORDER BY name LIMIT 10

Example 2: Complex Query

Input:

SELECT u.name, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at > '2024-01-01' GROUP BY u.id,u.name HAVING COUNT(o.id) > 5

Output:

SELECT u.name, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at > '2024-01-01' GROUP BY u.id, u.name HAVING COUNT(o.id) > 5

FAQ

Does the formatter validate SQL syntax?

The formatter focuses on formatting, not validation. Syntax errors won't prevent formatting but may produce unexpected results.

Which SQL dialects are supported?

The formatter works with most standard SQL syntax and supports MySQL, PostgreSQL, SQL Server, and SQLite dialects.

Can I preserve comments?

Yes, the formatter preserves both single-line (-- ) and multi-line (/* */) comments.