How to Format SQL Queries
SQL queries can quickly become hard to read when writing complex joins, subqueries, or analytics aggregations. Poorly formatted SQL is difficult for developers to review, debug, and optimize.
In this guide, we'll explain how to format and structure your SQL statements for maximum clarity.
Standard SQL Spacing
Consider this unformatted query:
select u.name,o.total from users u join orders o on u.id=o.user_id where o.status='paid' order by o.total desc;Compare it to the formatted version:
SELECT
u.name,
o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.status = 'paid'
ORDER BY o.total DESC;The formatted version makes the selected fields, tables, joins, filters, and sorting criteria immediately clear.
Capitalization Rules
Standard SQL formatting practices recommend capitalizing keyword clauses (like SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY) to distinguish them from field names, tables, and variables.
SQL Formatter
Format, beautify and indent database SQL queries.
Nested Spacing and Subqueries
For nested queries or subqueries, indent the subquery code blocks (usually using 2 or 4 spaces) to make it clear which query block executes first.
SELECT name
FROM users
WHERE id IN (
SELECT user_id
FROM orders
WHERE status = 'active'
);This hierarchy makes it easy to track query execution logic and optimize database queries.