How to Format SQL So Anyone Can Read It
Developer · October 17, 2026 · 1 min read
SQL queries often start small and grow into long, tangled statements. Formatting doesn't change what a query does, but it makes mistakes far easier to spot and reviews far faster.
A readable layout
SELECT o.id, c.name, SUM(i.price * i.quantity) AS total FROM orders AS o JOIN customers AS c ON c.id = o.customer_id JOIN items AS i ON i.order_id = o.id WHERE o.status = 'paid' GROUP BY o.id, c.name ORDER BY total DESC;
- Put each major clause (SELECT, FROM, WHERE, GROUP BY, ORDER BY) on its own line.
- Write keywords in capitals so they stand out from table and column names.
- Indent the list of columns and the join conditions.
- Give tables short but meaningful aliases and use them for every column.
- Pick one comma style, either at the end of lines or at the start, and keep to it.
Habits that prevent bugs
- Name the columns you need instead of using SELECT *, which breaks when a table changes.
- Break a long query into named steps with common table expressions (WITH).
- Put a condition on every join, so you don't multiply rows by accident.
- Use brackets in conditions that mix AND with OR.
Quotes inside text
A single quote ends a text value in SQL. To include one inside the text, write it twice, so O'Brien becomes 'O''Brien'. If you are building SQL from other text, the String Escape tool handles quoting for SQL and many other languages. Even so, programs should pass values to the database as parameters instead of building queries from text, which prevents SQL injection.
Use the tool
Paste a query into the SQL Formatter, choose your database dialect, and it lays the query out consistently. It can also shrink a query to one line, leaving quoted text untouched, for places where you need it compact.