How to Write Readable SQL: Formatting Rules Teams Actually Follow
Seven layout conventions for readable SQL, a worked query in three layouts, and an honest look at what a keyword-based formatter gets wrong.
Why readable SQL is worth the effort
A query is written once and read many times: in code review, during an incident, or six months later by someone who did not write it. A 200-character query on one line hides its joins and filters. The same query laid out in a consistent shape lets a reviewer see in seconds which tables are involved, how they connect and which rows are filtered out. Most readability problems come from a handful of habits, and all of them are about layout, not cleverness.
This post covers the layout conventions that are widely used, shows how the SQL formatter behaves on real queries, and is direct about what it leaves for you to fix by hand. The conventions are common practice, not a standard; if your team already has a style guide, that guide wins.
Seven conventions that make queries easier to review
- One clause per line. Start
SELECT,FROM,WHERE,GROUP BY,HAVING,ORDER BYandLIMITon their own lines, aligned at the left margin. The shape of the query is then visible before you read any detail. - One selected column per line once there are more than three or four. Adding or removing a column then produces a one-line diff in version control.
- Keep each join with its condition. Write
LEFT JOIN orders oon one line andON o.customer_id = c.iddirectly beneath it, indented. Never separate a join from the condition that belongs to it. - Start filter lines with
ANDorOR. Putting the operator at the start of the line makes it easy to comment out a single condition while debugging. - Use short but meaningful aliases.
cfor customers andofor orders read well;t1andt2force the reader to look back at theFROMclause every time. - Name columns instead of using
SELECT *in application code. The query then documents what the code depends on, and adding a column to a table does not silently change what the query returns. - Be consistent about keyword case. Upper-case keywords and lower-case identifiers is the most common choice. Which one you pick matters less than every query in a codebase following the same one.
A worked example: one query, three layouts
Here is a realistic reporting query as it often arrives from a log file or an ORM's debug output:
SELECT c.name, COUNT(o.id) AS order_count FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE c.city = 'Pune' AND o.status IN ('paid','shipped') GROUP BY c.name HAVING COUNT(o.id) > 2 ORDER BY order_count DESC LIMIT 10
Pasted into the SQL formatter, it comes back like this:
SELECT c.name,COUNT(o.id)AS order_countFROM customers cLEFTJOIN orders oON o.customer_id = c.idWHERE c.city = 'Pune'AND o.statusIN ('paid','shipped')GROUP BY c.nameHAVINGCOUNT(o.id) > 2ORDER BY order_count DESCLIMIT 10
That is already far easier to scan than one long line, and the major clauses are now visible. It is also not the layout a careful reviewer would want. The tool broke LEFT away from JOIN, split COUNT(o.id) from its alias, and cut o.status IN (...) in two. After a few minutes of manual tidying, the same query reads like this:
SELECTthenc.name,andCOUNT(o.id) AS order_count, each on its own indented lineFROM customers cLEFT JOIN orders owithON o.customer_id = c.idindented beneath itWHERE c.city = 'Pune'and, on the next line,AND o.status IN ('paid', 'shipped')GROUP BY c.nameHAVING COUNT(o.id) > 2ORDER BY order_count DESCLIMIT 10
The practical workflow is: format first to get the skeleton, then merge the lines that were split too aggressively and add indentation. That takes a minute and is much faster than breaking up a long line by hand.
What the SQL formatter does, exactly
The tool inserts a line break before each of a fixed list of keywords: SELECT, FROM, WHERE, JOIN, LEFT, RIGHT, INNER, OUTER, ON, AND, OR, NOT, IN, LIKE, BETWEEN, ORDER BY, GROUP BY, HAVING, LIMIT, OFFSET, INSERT INTO, VALUES, UPDATE, SET, DELETE FROM, CREATE TABLE, ALTER TABLE, DROP TABLE, UNION, UNION ALL, AS, DISTINCT and the function names COUNT, SUM, AVG, MAX and MIN. Matching ignores case and keeps whatever capitalisation you typed. It runs entirely in your browser.
It changes whitespace only. It does not upper-case keywords, does not indent, and does not validate the query.
Limits and what the tool does not cover
These are the cases where you have to look at the output yourself:
- Over-splitting. Because
AND,IN,AS,ONand the aggregate names all trigger a break, simple expressions end up on several lines, as the example above shows.LEFTandJOINland on separate lines, and so do a function call and its alias. - Text inside string literals. The tool cannot tell a keyword from a word inside quotes. A filter such as
body LIKE '%this and that%'comes back with the string cut in two at the wordand, which changes the value you are searching for. Always check quoted values after formatting. - Column or table names that match a keyword. A column called
count,setormaxwill be split onto its own line like a keyword. - No indentation. Subqueries,
CASEexpressions and join conditions are not indented under their parents, so nested queries still need manual layout. - No dialect handling and no syntax check. It treats MySQL, PostgreSQL, SQL Server and Oracle the same way and will not tell you a query is invalid.
- Keywords are not upper-cased. If your team wants upper-case keywords, you need to apply that yourself.
For automated, team-wide formatting, use a dialect-aware formatter in your editor or CI so that every commit follows one style. The online tool is best for one-off jobs: making a pasted query readable enough to understand or discuss.
A short review checklist
Before you merge or share a query, run through this list:
- Can you name every table from the
FROMandJOINlines alone? - Does every join have its condition directly beneath it?
- Does the
WHEREclause put each condition on its own line, and is the use ofANDandORunambiguous? When both appear together, add brackets rather than relying on operator precedence. - Are all selected columns named, and do aliases explain themselves?
- If you used the formatter, did you re-read every quoted string and every column name that could match a keyword?
When you share queries in tickets or documents, replace real customer names, phone numbers and keys with placeholder values first. If the query comes from an API payload or log that also contains JSON, the JSON formatter handles that part, and the HTML formatter does the same job for markup.
Tools used in this article
- SQL Formatter — Reformat SQL by inserting a line break before each major keyword — a broad keyword list covering joins, clauses, and DDL statements.
- JSON Formatter — Pretty-print JSON with real 2-space indentation using the browser's native JSON parser — shows the exact parse error if your JSON is invalid.
- HTML Formatter — Reformat HTML with proper nested indentation based on tag depth — a lightweight tag-based indenter, not a full HTML parser.