SQL Formatter

SQL statement formatting and beautification tool

Tool Overview: SQL Formatter Tool

The SQL formatter tool can convert compressed or messy SQL statements into well-formatted, easy-to-read forms. It supports automatic indentation, line breaks, keyword capitalization, and also provides SQL compression functionality, suitable for various database systems.

What Is SQL Formatter Tool?

SQL Formatter Tool formats content with consistent indentation and layout for better readability.

How to Use

  1. Paste the content to format.
  2. Choose indentation and formatting options.
  3. Format and copy the output.

Common Use Cases

  • Normalize style before commit
  • Spot structure or syntax issues
  • Present clean snippets in docs

❓ FAQ

Q1: Formatting failed?
A: Check the input syntax before formatting.

Q2: Can I minify?
A: Use a compact option if available.

Q3: Keep comments?
A: Choose a mode that preserves comments.

✨ Key Features

  • 🎯 Smart Formatting: Automatically adds appropriate indentation and line breaks
  • 🔤 Keyword Capitalization: SQL keywords automatically converted to uppercase
  • 📐 Auto Indentation: Automatically adjusts indentation based on statement structure
  • 🗜️ SQL Compression: Removes extra spaces and line breaks, compresses SQL statements
  • 📋 One-click Copy: Formatted results can be directly copied for use
  • 🔧 Multi-database Support: Supports MySQL, PostgreSQL, SQLite, etc.

📖 Usage Examples

SQL Formatting Example

Original SQL:

SELECT u.id, u.name, u.email, p.title, p.content FROM users u LEFT JOIN posts p ON u.id = p.user_id WHERE u.status = 'active' AND p.published_at IS NOT NULL ORDER BY p.created_at DESC LIMIT 10;

After Formatting:

SELECT 
    u.id,
    u.name,
    u.email,
    p.title,
    p.content
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.status = 'active'
    AND p.published_at IS NOT NULL
ORDER BY p.created_at DESC
LIMIT 10;

Complex Query Formatting

Original SQL:

SELECT COUNT(*) as total, AVG(salary) as avg_salary, department FROM employees WHERE hire_date >= '2020-01-01' GROUP BY department HAVING COUNT(*) > 5 ORDER BY avg_salary DESC;

After Formatting:

SELECT 
    COUNT(*) AS total,
    AVG(salary) AS avg_salary,
    department
FROM employees
WHERE hire_date >= '2020-01-01'
GROUP BY department
HAVING COUNT(*) > 5
ORDER BY avg_salary DESC;

🎯 Application Scenarios

1. Code Review and Maintenance

Improve SQL code readability for team collaboration:

-- Before formatting: hard to read
SELECT o.order_id,o.order_date,c.customer_name,SUM(oi.quantity*oi.price) as total FROM orders o JOIN customers c ON o.customer_id=c.customer_id JOIN order_items oi ON o.order_id=oi.order_id WHERE o.order_date BETWEEN '2024-01-01' AND '2024-12-31' GROUP BY o.order_id,o.order_date,c.customer_name HAVING total>1000 ORDER BY total DESC;

-- After formatting: clear and readable
SELECT 
    o.order_id,
    o.order_date,
    c.customer_name,
    SUM(oi.quantity * oi.price) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY 
    o.order_id,
    o.order_date,
    c.customer_name
HAVING total > 1000
ORDER BY total DESC;

2. Database Migration Scripts

Organize migration scripts to ensure execution accuracy:

-- Create table structure
CREATE TABLE user_profiles (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    phone VARCHAR(20),
    address TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- Insert initial data
INSERT INTO user_profiles (
    user_id,
    first_name,
    last_name,
    email,
    phone,
    address
) VALUES 
    (1, 'John', 'Doe', 'john.doe@example.com', '555-0123', '123 Main St, New York'),
    (2, 'Jane', 'Smith', 'jane.smith@example.com', '555-0124', '456 Oak Ave, Los Angeles'),
    (3, 'Bob', 'Johnson', 'bob.johnson@example.com', '555-0125', '789 Pine Rd, Chicago');

3. Performance Optimization Analysis

Format complex queries for performance analysis:

-- Query before performance optimization
SELECT 
    p.product_name,
    c.category_name,
    s.supplier_name,
    i.quantity_in_stock,
    i.reorder_level,
    CASE 
        WHEN i.quantity_in_stock <= i.reorder_level THEN 'Need Restock'
        WHEN i.quantity_in_stock <= i.reorder_level * 2 THEN 'Low Stock'
        ELSE 'Sufficient Stock'
    END AS stock_status
FROM products p
INNER JOIN categories c ON p.category_id = c.category_id
INNER JOIN suppliers s ON p.supplier_id = s.supplier_id
INNER JOIN inventory i ON p.product_id = i.product_id
WHERE p.discontinued = 0
    AND i.quantity_in_stock > 0
ORDER BY 
    c.category_name,
    stock_status,
    p.product_name;

4. Documentation Generation

Generate formatted SQL examples for database documentation:

-- User permission management example
WITH user_permissions AS (
    SELECT 
        u.user_id,
        u.username,
        r.role_name,
        p.permission_name
    FROM users u
    JOIN user_roles ur ON u.user_id = ur.user_id
    JOIN roles r ON ur.role_id = r.role_id
    JOIN role_permissions rp ON r.role_id = rp.role_id
    JOIN permissions p ON rp.permission_id = p.permission_id
    WHERE u.is_active = 1
)
SELECT 
    username,
    role_name,
    STRING_AGG(permission_name, ', ') AS permissions
FROM user_permissions
GROUP BY username, role_name
ORDER BY username;

🔧 Technical Details

Formatting Rules

SQL formatting follows these rules:

Keyword Handling:

  • SELECT, FROM, WHERE, JOIN keywords in uppercase
  • Each major clause on its own line
  • Subqueries properly indented

Fields and Table Names:

  • Multiple fields each on separate lines
  • Comma-first or comma-last style (configurable)
  • Table aliases kept concise

Conditional Statements:

  • WHERE conditions with appropriate line breaks
  • AND/OR logical operators aligned
  • Complex conditions grouped with parentheses

JOIN Statements:

  • Each JOIN on its own line
  • ON conditions aligned with JOIN
  • Multiple JOIN conditions vertically aligned

Compression Rules

SQL compression functionality:

Whitespace Handling:

  • Remove extra spaces and tabs
  • Preserve necessary space separators
  • Remove empty lines and comments

Statement Merging:

  • Merge multi-line statements into single lines
  • Maintain SQL syntax correctness
  • Reduce file size

💡 Usage Tips

  • Batch Processing: Can format multiple SQL statements simultaneously
  • Preserve Comments: Option to keep or remove comments during formatting
  • Custom Indentation: Support for 2 spaces, 4 spaces, or tab indentation
  • Keyword Case: Choose uppercase, lowercase, or keep original case

⚠️ Important Notes

  • Syntax Check: Ensure SQL syntax is correct before formatting
  • Database Differences: Different databases may have slightly different syntax
  • Complex Statements: Extremely complex SQL may require manual adjustment
  • Backup Original: Recommend backing up original SQL before formatting

🚀 Getting Started

  1. Input SQL: Paste the SQL statement to be formatted in the input box
  2. Choose Operation: Click "Format" or "Compress" button
  3. View Results: Check the processed SQL in the output box
  4. Copy for Use: Click "Copy" button to copy results to clipboard
  5. Example Demo: Click "Load Example" to view demo data

Tip: This tool processes locally on the client side and does not upload your SQL statements to the server, ensuring data security.