SQL Formatting Standards & Best Practices
5 Min Read• Published 2026
Why SQL Formatting Matters
SQL is a declarative language, meaning it details *what* data to retrieve rather than *how* to fetch it. While database engines parse compact, single-line queries with ease, human developers require structured layouts to audit logic, locate joins, and perform optimization.
Rule 1: Capitalize All Keywords
Always capitalize SQL keywords (`SELECT`, `FROM`, `WHERE`, `JOIN`, `GROUP BY`, `ORDER BY`, `AND`, `OR`). Keep tables, columns, and aliases in lowercase or camelCase:
-- Bad Form select id, username from users where status = 'active'; -- Standard Form SELECT id, username FROM users WHERE status = 'active';
Rule 2: Indent Joins and Nesting
Place each join on a new line and align the `ON` condition. Indent nested subqueries or CTEs (Common Table Expressions) by 2 or 4 spaces:
WITH active_orders AS ( SELECT user_id, SUM(amount) as total FROM orders WHERE status = 'completed' GROUP BY user_id ) SELECT u.username, o.total FROM users u JOIN active_orders o ON u.id = o.user_id;
