SQL Formatting Guide
Why Format SQL?
Properly formatted SQL is easier to read, debug, and maintain. Whether you're writing a quick query or building complex stored procedures, consistent formatting helps your team understand code faster.
Common Formatting Rules
- Uppercase keywords: SELECT, FROM, WHERE, JOIN make keywords stand out
- One clause per line: Each major clause (SELECT, FROM, WHERE) starts on its own line
- Indent sub-clauses: AND, OR, ON are indented under their parent clause
- Align columns: List selected columns vertically for readability
- Consistent comma placement: Either leading or trailing commas, but be consistent
Before & After
-- Before (hard to read) select u.id,u.name,o.total from users u inner join orders o on u.id=o.user_id where o.total>100 and u.active=true order by o.total desc limit 10; -- After (formatted) SELECT u.id, u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.total > 100 AND u.active = true ORDER BY o.total DESC LIMIT 10;
Tips for Complex Queries
- Use CTEs (WITH clauses) to break complex queries into named steps
- Comment sections of long queries with -- or /* */
- Alias tables with short, meaningful names (u for users, o for orders)
- Use subqueries sparingly. CTEs are usually more readable
SQL Style Guides
Popular SQL style guides include the Simon Holywell SQL Style Guide and GitLab's SQL style guide. Most agree on uppercase keywords and one-clause-per-line formatting.