SQL Formatting Best Practices
Writing SQL that functions correctly is only half the battle. As database schemas grow and queries require complex operations (such as joins, CTEs, window functions, and analytics aggregations), keeping your SQL readable is key for team reviews and long-term maintenance.
In this guide, we'll cover the best practices for formatting production-ready SQL queries.
Using Common Table Expressions (CTEs)
Rather than writing deep nested subqueries, write Common Table Expressions (CTEs) using the WITH keyword. CTEs act like temporary tables, breaking complex queries into logical, readable steps.
Avoid Nested Subqueries:
SELECT name FROM (SELECT * FROM users WHERE status = 'active') WHERE id = 1;Use CTEs instead:
WITH active_users AS (
SELECT id, name
FROM users
WHERE status = 'active'
)
SELECT name
FROM active_users
WHERE id = 1;CTEs improve readability by laying out the query execution steps sequentially.
JOIN Layout Guidelines
For queries involving multiple joins, place each JOIN and its corresponding ON criteria on a new line. Grouping fields logically keeps your code organized.
SELECT
u.name,
p.title,
o.order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
LEFT JOIN products p ON o.product_id = p.id
WHERE u.active = true;SQL Formatter
Format, beautify and indent database SQL queries.
u for users, o for orders) to make it clear which fields belong to which tables.