Skip to main content
Guide 7 min read

How to Format and Read Long SQL Queries: Style Rules That Save Time

You open a query that runs 200 lines. It sits on a single block of text, with three levels of subqueries and aliases like a, b and t2. You scroll up and down looking for the filter, and ten minutes later you still can’t say what it returns. When you format long SQL queries well, that scene disappears. The same query reads like an outline, and a bug has fewer places to hide.

This guide gives you a set of style rules you can apply today, plus a method for reading a long query someone else wrote. You’ll see a before and after example, the habits that matter most and a checklist for your team.

Why long queries get hard to read

SQL starts out like a plain sentence. Select these columns from that table where this is true. Then the requirements grow. You add a join, a second join, a filter, a subquery inside the filter and a calculation inside the subquery. Nothing is wrong with any single step, but the whole thing turns into a maze.

Three things make it worse. Everything sits on one line, so your eye has nowhere to land. Aliases carry no meaning, so you keep flipping back to see what t2 stands for. And nested subqueries force you to read from the inside out, which isn’t how anyone thinks. Fix those three and most of the pain goes away.

Give every clause its own line

This is the biggest win, and it costs nothing. Use these layout rules:

  • Start each major clause on a new line: SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING and ORDER BY.
  • Put one column per line in the SELECT list, with an indent.
  • Put the ON condition of a join on its own indented line.
  • Put one condition per line in WHERE, and start the line with AND or OR so the logic stays visible.
  • Add a blank line between big blocks, like between two CTEs.
  • Use four spaces or two spaces, never a mix of tabs and spaces.

You don’t have to do this by hand. Paste the query into our SQL formatter and it applies a clean layout in one click. Our guide on writing readable SQL goes deeper on the thinking behind it.

Pick a keyword case and stick to it

Some teams write keywords in capitals and names in lowercase, so the structure jumps out. Others write everything in lowercase because it’s faster to type. Either choice works. What hurts is a query where half the keywords are capitals and half aren’t.

Got a pasted query in the wrong case? Our text case converter switches the whole block at once. Then check that string values in quotes didn’t change, because those are data and not keywords.

Name things so you can read them

Names do half the explaining. A few rules help:

  • Write AS every time you create an alias. A missing AS next to a missing comma causes bugs that are hard to spot.
  • Skip aliases like a, b and t1 in long queries. Use a short name with meaning, like po for paid orders.
  • Put the alias in front of every column in a query with joins, like c.name. The reader then knows which table each column comes from.
  • Name every calculated column, like total_spent. Don’t leave it as an anonymous expression.
  • Use snake_case for names, and avoid spaces and quotes in them.

Trailing commas or leading commas?

Trailing commas sit at the end of a line and match normal writing. Leading commas sit at the start of the next line. The leading style makes it easy to comment out the last column, and it shows cleaner changes when you review a diff. The trailing style looks more familiar to most readers.

Honestly, either one is fine. The only bad choice is mixing them. Pick one for the team and let a formatter enforce it.

Replace nested subqueries with CTEs

A common table expression, or CTE, is a named block that starts with WITH. Each one does a single job, and the final query reads top to bottom like a recipe. Here’s a messy query first:

select c.name,sum(o.total) as t from customers c join orders o on c.id=o.customer_id where o.status='paid' and o.order_date>=:start_date and c.id in (select customer_id from vip_list) group by c.name having sum(o.total)>1000 order by t desc

And here’s the same logic, formatted and split into CTEs:

WITH paid_orders AS (
    SELECT
        customer_id,
        total
    FROM orders
    WHERE status = 'paid'
        AND order_date >= :start_date
),

vip_customers AS (
    SELECT customer_id
    FROM vip_list
)

SELECT
    c.name AS customer_name,
    SUM(po.total) AS total_spent
FROM customers AS c
INNER JOIN paid_orders AS po
    ON po.customer_id = c.id
INNER JOIN vip_customers AS v
    ON v.customer_id = c.id
GROUP BY c.name
HAVING SUM(po.total) > 1000
ORDER BY total_spent DESC

The second version is longer, and it’s still faster to read. The CTE names tell you the story before you read a single condition: paid orders, VIP customers, then a total per customer. One caveat. The rewrite assumes each customer appears once in the VIP list, since a join repeats rows when it finds duplicates. Also check your database’s documentation, because some engines handle CTEs differently when they plan a query.

Skip SELECT star

The star pulls every column, which is fine while you explore a table. In a saved query it causes trouble. Someone adds a column and your output changes. A reader can’t tell which columns matter. And a query that feeds an app can break when the table changes shape.

List the columns you need, one per line. It takes a minute and the reader gets the output at a glance. To find leftover stars across a folder of queries, build a pattern that matches the word SELECT followed by spaces and a literal star, and test it in our regex tester.

Comment the why, not the what

The code already says what it does. A comment should say why. Why does this filter drop test accounts? Why does this join use a left join instead of an inner join? Why 1000 and not 500? Those answers vanish when the author leaves.

Use block comments, which start with a slash and a star and end with a star and a slash. Line comments break when a tool joins your lines into one, and then the rest of the query turns into a comment. Here’s a short sample:

/* Test accounts are excluded because finance reports them separately */
WHERE c.is_test = FALSE

How to read a long query someone else wrote

Reading is a skill, and it follows an order. The database doesn’t run a query from top to bottom. It works through FROM and the joins first, then WHERE, GROUP BY, HAVING, SELECT and last of all ORDER BY. Read in that order and the query makes more sense. Follow these steps:

  1. Format it first. Paste it into the SQL formatter so you read a clean layout.
  2. Read the CTE names. They give you the outline.
  3. Look at the final SELECT to see what the query returns.
  4. Read FROM and the joins and ask one question: what does one row stand for? One order? One customer? One day?
  5. Read WHERE to see what gets filtered out.
  6. Read GROUP BY and HAVING to see how the rows collapse.
  7. Run each CTE alone with a small row limit and look at the output.
  8. Write down anything unclear, then ask the author or add a comment.

Step 7 does the most. A query you can’t follow in your head is easy to follow one block at a time.

Habits that make queries harder to read

These slips cost the most time:

  • Writing the whole query on one line.
  • Nesting subqueries three levels deep.
  • Using one letter aliases in a query with many joins.
  • Mixing OR and AND without brackets, so the reader can’t tell how they combine.
  • Using the old comma join style, where tables sit in FROM and the join condition hides in WHERE.
  • Leaving old commented code in the file.
  • Giving a calculated column no name.
  • Saving a query with a star in the SELECT list.

Make the style automatic

Style rules only work when everyone follows them, and people forget. So take the choice out of their hands. Agree on one short style guide, run a formatter before every commit and let the tool settle arguments about commas and capitals.

One more tip for reviews. Put a pure formatting change in its own commit, with no logic changes mixed in. Then compare the old and new versions in our text diff checker and confirm that only whitespace moved. Your reviewer will thank you.

A checklist before you share a query

Run through this list once:

  1. Every major clause starts on its own line.
  2. Each column in SELECT sits on its own line.
  3. Keywords use one case from top to bottom.
  4. Every alias uses AS and has a name with meaning.
  5. Columns carry their table alias in any query with joins.
  6. Nested subqueries became named CTEs.
  7. The SELECT list names its columns, with no star.
  8. Comments explain the why, and they use block style.

The short version

Put each clause and each column on its own line, pick one keyword case, and give aliases real names. Replace nested subqueries with CTEs, list your columns instead of using a star and comment the why. To read someone else’s query, format it, read the CTE names, find the grain of each row and run one block at a time.

Take the longest query you wrote this month and run it through the SQL formatter today. Then rename two aliases and split out one CTE. You’ll feel the difference at once.

Free browser based tools on Black Claaw to format queries, switch keyword case, find patterns and compare versions.

View all tools

Advertisement