SQL queries, like any code, require careful formatting. A well-formatted query is easier to read, debug, and maintain. This article covers SQL formatting best practices.
Why Format SQL
Minified SQL crammed into a single long line is a common sight when copying from logs, ORM output, or monitoring tools. Such a query is extremely difficult to analyze:
SELECT u.id,u.name,o.total FROM users u JOIN orders o ON u.id=o.user_id WHERE o.status='paid' AND o.created_at>'2024-01-01' ORDER BY o.total DESC LIMIT 10
After formatting, the same query becomes clear at a glance.
Formatting Rules
- Keywords in uppercase: SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, HAVING, LIMIT, INSERT, UPDATE, DELETE.
- Each clause on a new line: SELECT, FROM, WHERE, JOIN, and others start a new line.
- Indentation for nesting: conditions after WHERE, columns after SELECT, and subqueries are indented.
- Each JOIN on its own line: with the ON condition specified.
SQL Minification
The reverse operation — minification — removes all unnecessary whitespace and line breaks. This is useful when embedding SQL in program code, sending it via an API, or saving it in configuration files.
Conclusion
Format any SQL query instantly with our online SQL formatter. The tool supports all major SQL constructs and correctly handles nested subqueries.