Complete Guide to SQL Formatting and Best Practices
Properly formatted SQL improves readability, reduces bugs, and makes collaboration easier. This guide explains formatting rules, conventions, and practical tips for writing clean, maintainable SQL across different dialects.
Why SQL Formatting Matters
- Readability: Clear structure helps you and your team understand queries faster
- Maintainability: Easier to update queries without introducing errors
- Debuggability: Logical line breaks and indentation surface mistakes early
- Consistency: Shared conventions reduce cognitive load across projects
- Performance Reviews: Clean SQL is easier to optimize and review
Core Formatting Rules
- Keywords: Use UPPERCASE for SQL keywords (SELECT, FROM, WHERE, JOIN)
- Indentation: Indent nested queries and clause continuations consistently
- Line Breaks: Place major clauses on new lines (FROM, WHERE, GROUP BY)
- Joins: Put each JOIN on its own line with ON conditions indented
- Commas: Place commas at the end of lines for column lists
Example: Clean vs. Messy
-- Messy
select u.id,u.name,o.total from users u left join orders o on u.id=o.user_id
where u.status='active' and o.total>100 order by o.total desc;
-- Clean
SELECT
u.id,
u.name,
o.total
FROM users u
LEFT JOIN orders o
ON u.id = o.user_id
WHERE u.status = 'active'
AND o.total > 100
ORDER BY o.total DESC;
Dialect Differences
- MySQL: Backticks for identifiers (`users`), LIMIT syntax
- PostgreSQL: Double-quotes for identifiers, powerful window functions
- SQL Server: TOP syntax, square brackets for identifiers
- Oracle: NVL/DECODE, ROWNUM, different date functions
Safety and Performance Tips
- Prefer explicit column lists over SELECT *
- Qualify columns with table aliases to avoid ambiguity
- Use WHERE filters before GROUP BY to reduce intermediate rows
- Index join keys and frequently filtered columns
- Beware of implicit conversions; cast explicitly when needed
Common Anti-Patterns
- Nesting subqueries unnecessarily where JOINs suffice
- Using SELECT DISTINCT to hide duplicate-creation bugs
- Applying functions to indexed columns in WHERE (prevents index use)
- Mixing presentation logic (formatting) inside SQL (do it in code)