Back to Blog

SQL Query Formatting Best Practices

February 15, 2025 · 8 min read

Why SQL Formatting Matters

SQL queries can range from simple single-line statements to complex multi-join queries spanning dozens of lines. Without consistent formatting, these queries become difficult to read, debug, and maintain. Poor formatting is a leading cause of subtle bugs in production — a misplaced WHERE clause or a missing JOIN condition can silently return incorrect results.

Core Formatting Rules

1. Uppercase SQL Keywords

The most universally accepted convention is to write SQL keywords in uppercase. This creates a clear visual distinction between keywords and identifiers:

-- ✅ Good: Keywords uppercase
SELECT u.name, u.email, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.created_at > '2024-01-01'
ORDER BY o.total DESC;

-- ❌ Bad: All lowercase
select u.name, u.email, o.total from users u inner join orders o on u.id = o.user_id where o.created_at > '2024-01-01' order by o.total desc;

2. One Clause Per Line

Each major SQL clause (SELECT, FROM, WHERE, JOIN, ORDER BY) should start on its own line. This makes the query's logical flow immediately apparent.

3. Indent Subordinate Elements

Column lists, AND/OR conditions, and subquery bodies should be indented to show hierarchy:

SELECT
    u.name,
    u.email,
    COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o
    ON u.id = o.user_id
    AND o.status = 'completed'
WHERE
    u.is_active = 1
    AND u.created_at > '2024-01-01'
GROUP BY u.name, u.email
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC;

4. Use Meaningful Table Aliases

Instead of arbitrary single letters, use abbreviated but readable aliases. For example, use usr for users and ord for orders, especially in complex queries with many joins.

5. Format Subqueries Clearly

Subqueries should be indented and enclosed in their own block, making it easy to understand the query's nesting structure:

SELECT name, email
FROM users
WHERE id IN (
    SELECT user_id
    FROM orders
    WHERE total > 1000
    GROUP BY user_id
    HAVING COUNT(*) > 3
);

Dialect-Specific Tips

MySQL

  • Use backticks (`table_name`) for reserved words used as identifiers.
  • Prefer LIMIT over vendor-specific pagination.

PostgreSQL

  • Use ILIKE for case-insensitive matching.
  • Take advantage of CTEs (Common Table Expressions) to break complex queries into readable named steps.

SQL Server (T-SQL)

  • Use square brackets ([column]) for reserved words.
  • Prefer TOP or OFFSET/FETCH for pagination.

Common Mistakes to Avoid

  • Writing entire queries on a single line.
  • Using SELECT * in production queries — always specify columns explicitly.
  • Missing aliases in multi-table queries, leading to ambiguous column references.
  • Forgetting to terminate queries with a semicolon.

Try it yourself

Format SQL queries with dialect-aware capitalization and indentation.

Open Tool