How to Format SQL Queries So Your Team Can Read Them

SQL is a language for asking questions about data, but many queries are written as if only the database needs to understand them. A long query on one line, with lowercase keywords and no clear structure, can be correct and still be painful to read. When a teammate needs to change it, or when you return to it months later, that pain turns into time, mistakes, and hesitation.

Formatting SQL is about making the intent of a query visible. A reader should be able to see which columns are selected, which tables are involved, how the tables are joined, which rows are filtered, and how the results are grouped and sorted, without decoding a wall of text. This guide shows a simple, consistent style that works for everyday SELECT queries, with a worked example, and explains how to reformat safely.

You do not need a special tool to start, although a formatter can help once you know the rules. What you need is a clear layout, consistent capitalization, and a habit of testing after you change a query. Those three habits will make your queries easier to review, easier to debug, and easier to trust.

What Readable SQL Looks Like

Readable SQL starts each major clause on its own line. SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, and ORDER BY each get a line, so the structure of the query is obvious at a glance. Within SELECT, each column gets its own line when the list is long, and commas sit at the end of each line. That layout makes it easy to add, remove, or reorder a column without disturbing the rest of the query.

Keywords are written in uppercase, while table and column names use the case that matches the database. Uppercase keywords stand out, so a reader can scan for WHERE or ORDER BY without reading every word. Consistent capitalization also helps in code review, because a change to a keyword is easy to spot. Aliases are short and meaningful, and they are used consistently throughout the query.

Indentation shows which parts belong together. Conditions in a WHERE clause are indented under WHERE. Join conditions sit with their JOIN. Subqueries are indented as a block, with their own internal formatting. Blank lines can separate a main query from a subquery, but too many blank lines can make a short query feel scattered. The goal is a layout that mirrors the logic.

How to Format SQL Step by Step

Start by putting one clause per line. Write SELECT on its own line, then list the columns. Write FROM on its own line, then name the main table. Write each JOIN on its own line, with its ON condition on the same line or indented below it. Write WHERE on its own line, then list each condition on its own line, joined by AND or OR. Write GROUP BY, HAVING, and ORDER BY on their own lines as well.

Next, make keywords uppercase. That includes SELECT, FROM, WHERE, JOIN, ON, AND, OR, GROUP BY, HAVING, ORDER BY, ASC, DESC, and AS. Keep table and column names in the style your database uses, and do not change their spelling while formatting. Formatting should change layout and capitalization of keywords, not the names of things.

Align related items. If a SELECT list has several columns, put each column on its own line and indent them under SELECT. If a WHERE clause has several conditions, put each condition on its own line and indent them under WHERE. If a query uses table aliases, use the alias before every column that comes from that table, so it is clear where each column comes from. For example, a customer name from a customers table and an order total from an orders table should not be ambiguous.

Break long lines. A long condition with several AND and OR parts is easier to read when each part is on its own line and parentheses show the grouping. A long list of columns is easier to read when it is vertical rather than horizontal. A long CASE expression is easier to read when each WHEN, THEN, and ELSE sits on its own line. Short lines make version-control differences cleaner, because changing one condition changes one line.

Finally, end the query with a semicolon when your tool expects one, and keep a consistent style for the whole file. If your team uses a formatter, let it apply the style and review its output. If you format by hand, follow the same rules every time so that all queries in a project look like they were written by one person.

Worked Example: A SELECT Query Made Clear

Imagine a query that lists recent orders with customer names and totals. In its cramped form, it might select columns, join two tables, filter by status and date, group results, and sort them, all in a few long lines. The logic might be correct, but a reader has to work hard to see which part does what. A small change, such as adding a filter for a region, could easily land in the wrong clause.

Below is a readable version of the same idea. Each clause starts on its own line, keywords are uppercase, and the columns and conditions are listed vertically. The query asks for the customer name, the order date, and the total amount for completed orders in the last year, grouped by customer and ordered by total.

SELECT
  c.customer_name,
  o.order_date,
  SUM(o.amount) AS total_amount
FROM orders AS o
JOIN customers AS c
  ON c.customer_id = o.customer_id
WHERE o.status = 'completed'
  AND o.order_date >= '2025-01-01'
GROUP BY
  c.customer_name,
  o.order_date
ORDER BY total_amount DESC;

To produce this version, follow a short routine. First, identify each clause and give it its own line. Second, list the SELECT columns one per line. Third, write the JOIN and its ON condition clearly, with the join condition indented. Fourth, list each WHERE condition on its own line. Fifth, check that the GROUP BY columns match the non-aggregated SELECT columns, and that the ORDER BY refers to a column or alias that exists. Sixth, read the query aloud in plain language: select these columns from these tables, join them on this key, keep only these rows, group by these columns, and sort by total.

The same routine works for longer queries. Format one query at a time, and do not reformat and change logic in the same step unless you have a way to test the result. If a query uses a subquery, format the inner query first, then the outer query, and indent the inner query as a block so the nesting is visible.

Do Not Reformat Without Testing, Keep the Original Query

Formatting should not change what a query returns, but a careless edit can. Moving a parenthesis, changing an AND to an OR, deleting a condition, or changing a join can change the result set. That is why you should keep the original query before you reformat, and test the formatted version against it. Save the original in version control, in a comment, or in a separate file, so you can compare the two versions if the results differ.

Testing can be simple. Run the original query and the formatted query on the same data, and compare the row count and a sample of rows. If your database tool shows an execution plan, compare that too. If you have a test database, use it rather than a production database. If you must run a query on production data, use a read-only SELECT and avoid changing data while you test formatting.

When you reformat a query that other people use, tell them what you changed. A change that only affects whitespace is safe, but a change that moves a condition or renames an alias can affect other code. A short note in a code review, such as formatting only, no logic change, helps reviewers focus on whether the logic is unchanged. If a reviewer finds a difference, revert and investigate before continuing.

Common Mistakes That Hurt Readability

One common mistake is mixing keyword cases in the same file. SELECT in one query and select in another makes the file look inconsistent. Another mistake is putting all clauses on one line to save space. That may look compact, but it hides the structure and makes editing harder. A third mistake is using vague aliases, such as a, b, and c, for tables. Short aliases are fine when they are meaningful, such as o for orders and c for customers, but single letters that do not match the table names make the query harder to follow.

Another problem is formatting without fixing unclear names. If a column is named amount, formatting will not tell the reader whether it is a total, a tax, or a discount. Good names matter as much as good spacing. When you format, also look for names that can be made clearer with an alias, such as total_amount for a sum. Use AS for aliases, because it makes the alias explicit.

Finally, avoid formatting a query that is already too complex without asking whether it should be broken into steps. A very long query with many joins and subqueries may be correct, but it may be easier to maintain as a view, a common table expression, or a series of simpler queries. Formatting will make the complexity visible, which is good, but it will not make the logic simple. If a formatted query is still hard to follow, that is a sign to simplify the structure.

Limitations

Formatting improves readability, but it does not prove that a query is correct. A beautifully formatted query can still return the wrong rows, miss a filter, or join tables incorrectly. Formatting also does not replace testing, review, or an understanding of the data. A formatter can enforce spacing and capitalization, but it cannot decide whether a condition is correct or whether a join should be an inner join or a left join.

Formatting rules also depend on the database and the team. Different databases have different functions, different ways to handle dates, and different rules for quoting identifiers. A team may use a formatter with its own defaults, or a style guide that differs from the one in this guide. In those cases, follow the project convention rather than imposing a personal preference. The goal is shared readability, and a formatter configuration is a good way to record that choice.

Some queries should be left alone. Generated queries, queries embedded in tools, and queries that are part of a migration may need to stay in their original form. If you reformat them, you can make future updates harder and lose the ability to compare your copy with the original. Keep generated queries separate from hand-written queries, and format only the queries you own and maintain.

Frequently Asked Questions

Should SQL keywords be uppercase?

Uppercase keywords are a widely used convention because they make the structure of a query easy to scan. SELECT, FROM, WHERE, JOIN, GROUP BY, and ORDER BY stand out when they are uppercase, while table and column names stay in their normal case. Either style can work if it is consistent, but uppercase keywords are recommended for team queries because they make reviews faster.

Should each clause be on its own line?

Yes, as a default. One clause per line makes the structure visible and makes it easy to add or remove a clause without disturbing the rest of the query. Each column in a long SELECT list and each condition in a long WHERE clause also deserves its own line. For very short queries, a single line can be acceptable, but for anything a teammate will need to read, vertical layout is clearer.

How do I safely reformat a query?

Keep the original query, reformat in small steps, and test the result. Run the original and the formatted query on the same data and compare the row count and a sample of rows. Use version control so you can revert if the results differ. If you change logic and formatting at the same time, it is harder to tell which change caused a problem, so separate the two when you can.

Does formatting change query performance?

Formatting alone should not change performance, because the database engine sees the same logic. Whitespace and keyword case do not change the execution plan in most systems. What can change performance is a change to the logic, such as a different join, a different filter, or a different grouping. That is why testing after formatting matters: it confirms that the logic, not only the layout, is unchanged.

Conclusion

Readable SQL comes from consistent habits: one clause per line, uppercase keywords, vertical lists for columns and conditions, clear aliases, and short lines. Keep the original query, test after reformatting, and separate formatting changes from logic changes. Over time, these habits make queries easier to review, easier to debug, and easier to trust. The next person who opens the query, even if that person is you, will be able to understand what it asks for without decoding a wall of crowded text.