Tools16 min read

    SQL Formatting: Writing Clean and Readable Database Queries

    Master SQL formatting to write clean, readable, and maintainable database queries. Learn best practices, formatting standards, and tools that make SQL code professional.

    Michael Chen

    Michael Chen

    Investment Analyst

    June 1, 2025
    SQL Formatting: Writing Clean and Readable Database Queries

    Introduction

    SQL is the language of databases, used by developers, data analysts, and database administrators worldwide. Yet, many SQL queries are poorly formatted, making them difficult to read, understand, and maintain.

    Well-formatted SQL is not just about aesthetics—it's about code quality, maintainability, and collaboration. This comprehensive guide will teach you how to format SQL queries professionally, making your database code clean, readable, and maintainable.

    Why SQL Formatting Matters

    Readability

    Poorly Formatted:

    SELECT u.id,u.name,u.email,o.total,o.date FROM users u JOIN orders o ON u.id=o.user_id WHERE u.active=1 AND o.date>'2024-01-01' ORDER BY o.total DESC;
    

    Well Formatted:

    SELECT 
        u.id,
        u.name,
        u.email,
        o.total,
        o.date
    FROM users u
    JOIN orders o ON u.id = o.user_id
    WHERE u.active = 1
        AND o.date > '2024-01-01'
    ORDER BY o.total DESC;
    

    Difference: The formatted version is immediately understandable.

    Maintainability

    Well-formatted SQL is:

    • Easier to debug: Problems are easier to spot
    • Easier to modify: Changes are less error-prone
    • Easier to review: Code reviews are more effective
    • Easier to document: Self-documenting code

    Collaboration

    When working in teams:

    • Consistent formatting reduces confusion
    • Easier code reviews
    • Faster onboarding
    • Better knowledge sharing

    SQL Formatting Standards

    1. Keywords

    Rule: Use uppercase for SQL keywords Why: Distinguishes keywords from identifiers

    SELECT, FROM, WHERE, JOIN, ORDER BY, GROUP BY
    

    2. Indentation

    Rule: Indent sub-clauses and nested queries Standard: 2 or 4 spaces (be consistent)

    SELECT 
        column1,
        column2
    FROM table1
    WHERE condition1
        AND condition2
    

    3. Line Breaks

    Rule: Put major clauses on separate lines Clauses: SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY

    SELECT columns
    FROM table
    WHERE conditions
    

    4. Commas

    Rule: Trailing commas or leading commas (be consistent) Trailing (common):

    SELECT 
        column1,
        column2,
        column3
    

    Leading (alternative):

    SELECT 
        column1
        , column2
        , column3
    

    5. Alignment

    Rule: Align similar elements Example: Align SELECT columns, WHERE conditions

    SELECT 
        user_id,
        user_name,
        user_email
    FROM users
    WHERE user_active = 1
        AND user_created > '2024-01-01'
    

    Formatting Different SQL Constructs

    SELECT Statements

    Basic Structure:

    SELECT 
        column1,
        column2,
        column3
    FROM table_name
    WHERE condition
    ORDER BY column1;
    

    With Aliases:

    SELECT 
        u.id AS user_id,
        u.name AS user_name,
        COUNT(o.id) AS order_count
    FROM users u
    JOIN orders o ON u.id = o.user_id
    GROUP BY u.id, u.name;
    

    JOINs

    INNER JOIN:

    SELECT 
        u.name,
        o.total
    FROM users u
    INNER JOIN orders o ON u.id = o.user_id;
    

    Multiple JOINs:

    SELECT 
        u.name,
        p.name AS product_name,
        oi.quantity
    FROM users u
    JOIN orders o ON u.id = o.user_id
    JOIN order_items oi ON o.id = oi.order_id
    JOIN products p ON oi.product_id = p.id;
    

    LEFT JOIN:

    SELECT 
        u.name,
        o.total
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE o.id IS NULL;  -- Users with no orders
    

    WHERE Clauses

    Simple Conditions:

    WHERE status = 'active'
        AND created_date > '2024-01-01'
    

    Complex Conditions:

    WHERE (status = 'active' OR status = 'pending')
        AND created_date > '2024-01-01'
        AND (user_id IN (1, 2, 3) OR email LIKE '%@example.com')
    

    Subqueries:

    WHERE user_id IN (
        SELECT id
        FROM users
        WHERE active = 1
    )
    

    GROUP BY and HAVING

    SELECT 
        category,
        COUNT(*) AS product_count,
        AVG(price) AS avg_price
    FROM products
    WHERE active = 1
    GROUP BY category
    HAVING COUNT(*) > 10
    ORDER BY product_count DESC;
    

    CASE Statements

    SELECT 
        name,
        CASE 
            WHEN age < 18 THEN 'Minor'
            WHEN age < 65 THEN 'Adult'
            ELSE 'Senior'
        END AS age_group
    FROM users;
    

    CTEs (Common Table Expressions)

    WITH active_users AS (
        SELECT 
            id,
            name,
            email
        FROM users
        WHERE active = 1
    ),
    user_orders AS (
        SELECT 
            u.id,
            COUNT(o.id) AS order_count
        FROM active_users u
        LEFT JOIN orders o ON u.id = o.user_id
        GROUP BY u.id
    )
    SELECT 
        u.name,
        COALESCE(uo.order_count, 0) AS orders
    FROM active_users u
    LEFT JOIN user_orders uo ON u.id = uo.id;
    

    Best Practices

    1. Be Consistent

    Rule: Pick a style and stick to it Why: Consistency reduces cognitive load

    2. Use Meaningful Aliases

    Bad:

    SELECT u.n, u.e FROM users u
    

    Good:

    SELECT 
        u.name,
        u.email
    FROM users u
    

    3. Format Long Queries

    Rule: Break long queries into logical sections Use: Comments to separate sections

    -- Get active users
    SELECT 
        u.id,
        u.name
    FROM users u
    WHERE u.active = 1
    
    -- Join with orders
    JOIN orders o ON u.id = o.user_id
    
    -- Filter recent orders
    WHERE o.date > '2024-01-01'
    

    Rule: Align similar clauses for easier scanning Example: Align all JOIN conditions

    SELECT 
        u.id,
        u.name,
        p.name AS product_name
    FROM users u
    JOIN orders o      ON u.id = o.user_id
    JOIN order_items oi ON o.id = oi.order_id
    JOIN products p    ON oi.product_id = p.id
    

    5. Use Comments Wisely

    Good Comments:

    -- Calculate total revenue for active users
    SELECT 
        u.id,
        SUM(o.total) AS total_revenue
    FROM users u
    JOIN orders o ON u.id = o.user_id
    WHERE u.active = 1  -- Only active users
    GROUP BY u.id;
    

    Bad Comments:

    -- Select users
    SELECT * FROM users;  -- This selects users
    

    Common Formatting Mistakes

    Mistake 1: Everything on One Line

    Problem: Unreadable, hard to debug Solution: Break into multiple lines

    Mistake 2: Inconsistent Indentation

    Problem: Hard to follow structure Solution: Use consistent indentation (2 or 4 spaces)

    Mistake 3: Mixed Case Keywords

    Problem: Inconsistent appearance Solution: Always use UPPERCASE for keywords

    Mistake 4: No Spaces Around Operators

    Problem: Hard to read Solution: Use spaces: column = value not column=value

    Mistake 5: Inconsistent Comma Placement

    Problem: Confusing Solution: Pick trailing or leading, stick with it

    Tools for SQL Formatting

    Online Formatters

    • SQLFormat: Free online SQL formatter
    • FreeFormatter: Multiple SQL dialects
    • SQL Beautifier: Quick formatting

    IDE Plugins

    • SQL Formatter (VS Code)
    • Poor Man's T-SQL Formatter (SQL Server)
    • A5 SQL Formatter (Various IDEs)

    Command Line Tools

    sqlformat (Python):

    pip install sqlparse
    sqlformat --reindent query.sql
    

    Database-Specific Tools

    • pgFormatter: PostgreSQL
    • SQL Server Management Studio: Built-in formatter
    • MySQL Workbench: Formatting options

    Formatting for Different Databases

    PostgreSQL

    SELECT 
        column1,
        column2
    FROM table_name
    WHERE condition;
    

    MySQL

    SELECT 
        `column1`,
        `column2`
    FROM `table_name`
    WHERE `condition`;
    

    SQL Server

    SELECT 
        [column1],
        [column2]
    FROM [table_name]
    WHERE [condition];
    

    Advanced Formatting Techniques

    1. Formatting Complex Queries

    Break into logical sections:

    -- Main query
    SELECT 
        columns
    FROM 
        -- Subquery or CTE
        (SELECT ...) AS subquery
    WHERE 
        conditions
    GROUP BY 
        columns
    HAVING 
        aggregate_conditions
    ORDER BY 
        columns;
    

    2. Formatting Stored Procedures

    CREATE PROCEDURE GetUserOrders
        @UserId INT
    AS
    BEGIN
        SET NOCOUNT ON;
        
        SELECT 
            o.id,
            o.date,
            o.total
        FROM orders o
        WHERE o.user_id = @UserId
        ORDER BY o.date DESC;
    END;
    

    3. Formatting Views

    CREATE VIEW ActiveUserOrders AS
    SELECT 
        u.id AS user_id,
        u.name AS user_name,
        o.id AS order_id,
        o.total AS order_total
    FROM users u
    JOIN orders o ON u.id = o.user_id
    WHERE u.active = 1;
    

    Conclusion

    SQL formatting is an essential skill for anyone working with databases. Well-formatted SQL is easier to read, understand, maintain, and debug. It improves collaboration and reduces errors.

    Remember:

    • Be consistent with your formatting style
    • Use proper indentation to show structure
    • Break long queries into readable sections
    • Use meaningful aliases and names
    • Format as you write to build good habits

    Start formatting your SQL queries today. Your future self (and your teammates) will thank you for it.

    Using Our SQL Tools

    At 1tool.dev, we offer a powerful SQL Formatter that helps you format SQL queries quickly and consistently. Whether you're cleaning up existing queries or writing new ones, our tool makes SQL formatting simple.

    Try our SQL formatter today and see how much more readable your database queries can be!

    Michael Chen

    Michael Chen

    Investment Analyst

    Investment analyst focusing on personal investment strategies and market trends.

    Related Posts

    UX Writing: Beyond Beautiful Words — The Science Behind Effective Interface Text
    Tools12 min read

    UX Writing: Beyond Beautiful Words — The Science Behind Effective Interface Text

    Discover why UX writing isn't about beautiful prose or perfect grammar, but about creating clear, contextual content that serves users at the right time and place. Learn the methodical approach professional UX writers take before writing a single word.

    Ismat BabirliMay 15, 2025
    This new IDE just destroyed VS Code and Copilot without even trying
    Tools12 min read

    This new IDE just destroyed VS Code and Copilot without even trying

    Discover how Windsurf IDE is changing the development landscape with its agentic capabilities, making VS Code and GitHub Copilot look outdated. Learn about its revolutionary features like Cascade and Supercomplete that are transforming how developers write code.

    Michael ChenMay 16, 2025
    10 Essential Text Formatting Tools Every Writer Needs
    Tools15 min read

    10 Essential Text Formatting Tools Every Writer Needs

    Discover the must-have text formatting tools that can transform your writing workflow. From case conversion to text cleaning, learn how these tools can save you hours and improve your content quality.

    Ismat BabirliMay 22, 2025