Making sense of a 200-line query you didn't write: how to read and understand inherited SQL

A method for reading a long SQL query you didn't write: format it, work outside-in through the CTEs, map the aliases, and check it against the real schema.

Someone hands you a query. It is 200 lines long, it has six CTEs, two levels of nested subqueries, aliases named a, b, and t3, and not one comment. It is in production, it is slow or wrong or both, and as of this morning it is your problem. The person who wrote it has left the company, or genuinely can’t remember it, or is you from eighteen months ago.

Reading SQL you didn’t write is a distinct skill, separate from writing it. When you write a query you build the model in your head first and the text second; when you inherit one you have only the text, and you have to reconstruct the model backwards. Staring at the whole thing until it makes sense is the slow way. There is a method, and it works from the outside in.

Disclosure: this blog is published by LumaSoft (LUMA sp. z o.o.), and I work on the tool mentioned near the end. The method below stands on its own, whatever tool you use.

Why is a query someone else wrote so hard to read?

Because a SQL statement is a single expression, not a sequence of steps. A 200-line Python function reads top to bottom: statement, statement, statement. A 200-line query is one SELECT with everything else hanging off it — joins, filters, grouping, window functions, nested subqueries — and your eye has nowhere obvious to start.

It is made worse by three things that cost the original author nothing and cost you everything: no formatting, no comments, and opaque aliases. FROM orders o JOIN order_lines ol ON ol.order_id = o.id is readable. The same thing as FROM orders a, order_lines b WHERE b.oid=a.id, crammed onto one line, is a puzzle. The logic is identical; the legibility is not.

So the first move, before you try to understand anything, is mechanical: reformat it. Run it through a formatter — one line per column in the SELECT, one line per join, consistent indentation for nested blocks — so the structure becomes visible. You are not changing the query, only making its shape apparent. Don’t skip this because it feels like busywork: half of “I can’t read this” is “this was never laid out to be read.”

Should you read a big query from the top or the bottom?

Neither, at first. You read it from the outside in, and the outermost thing is the final SELECT — the one whose columns are what the query actually returns. That list of output columns is the query’s purpose stated in its own words. Before you understand a single join, read the final select list and ask: what is this query supposed to produce? A row per customer with a lifetime total? One row per day with a running sum? That answer is the frame everything else hangs on.

It helps here to know that SQL does not execute in the order it is written. SQL Server’s documentation spells out the logical processing order of a SELECT: FROM and the joins first, then WHERE, then GROUP BY, then HAVING, and only then the SELECT list, DISTINCT, and ORDER BY. The clause you read first is almost the last thing the engine evaluates. So to trace a single output column, start at its name in the select list and work down and outward into the FROM to find where it comes from. The point of the query lives at the top; the data flow that feeds it starts at the bottom.

How do you take the CTEs and subqueries apart, one at a time?

A big query is almost never one big thing. It is several small queries stacked into one, and the stacking is usually done with Common Table Expressions — the WITH blocks at the top. The PostgreSQL manual puts it plainly: WITH provides a way to write auxiliary statements for use in a larger query, and those statements “can be thought of as defining temporary tables that exist just for one query.” That mental model is the key to reading them: each CTE is a named, self-contained result set. You can understand it entirely on its own, then treat it as a table everywhere it is used.

So take them in order. Read the first CTE in isolation — what does it return, at what grain, filtered how? Give it a plain-English label in your notes: “recent_orders = one row per order from the last 90 days.” Keep going until you have a short glossary of what each block produces. Nested subqueries in the FROM or WHERE get the same treatment: a subquery is just a CTE that wasn’t given a name, so name it yourself. By the time you reach the final SELECT, it is no longer joining six mysteries — it is joining six things you have already labelled.

How do you keep the tables and aliases straight?

Write them down. Not metaphorically — actually keep a running map as you read: o → orders, ol → order_lines, p → products, rc → the recent_customers CTE. Opaque single-letter aliases are the single biggest source of misreading in inherited SQL, because a.id = b.id tells you nothing about whether that join is sane, while orders.id = order_lines.order_id tells you immediately.

Pay special attention to two traps. The first is the same table joined twice under different aliases — a self-join, or two joins to a lookup table — where t1 and t2 are the same table playing two roles. The second is an alias that shadows a CTE name, so c in one place is a column and c in another is a CTE. Your alias map catches both, and it is what you will lean on hardest when the query turns out to be wrong and you have to explain to someone exactly which customer a predicate refers to.

How do you check the query’s assumptions against the real schema?

Here is the part that separates reading a query from understanding it. The text tells you what the author assumed; it does not tell you whether the assumptions are true. A join on o.customer_id = c.id assumes that relationship exists and is one-to-many in the direction you think. A WHERE status = 'shipped' assumes 'shipped' is a value that column actually holds, and not 'SHIPPED' or 3. A SUM over a joined table assumes the join doesn’t fan out rows and inflate the total.

None of that is visible in the query. It is visible in the schema — the real table definitions, keys, types, and the actual distinct values in a column. So the last step of reading is to check the query’s claims against the live database: does this foreign key exist, is this column really nullable, does this status enum really use the string the filter expects? This is the exact discipline of proving rather than guessing: the query is a set of hypotheses about a schema, and you confirm them against the schema instead of trusting them.

This is also the most natural place for an AI assistant to earn its keep. An assistant that explains a query by pattern-matching on the text alone is guessing, in exactly the way a language model guesses table names it has never seen. One that reads your real schema first, then translates the query against it, is grounded: it can tell you that status is an integer enum and 'shipped' would never match, or that this particular SUM is sitting on a one-to-many join and probably double-counts. That is not the model being clever; it is the model reading the same facts you would, faster.

Do you have to run it to understand it?

No — and that distinction matters more than it looks. Understanding an inherited query is a reading task: you want its meaning, its shape, its assumptions, its likely bugs. None of that requires executing it against production data — and running a 200-line query you don’t yet understand is how you find out the hard way that it locks a table or runs for nine minutes.

This is where a keyless, read-only-by-default approach fits the task exactly. Explaining someone else’s SQL needs the schema and the query text — the same two things that make the query readable to you. It does not need to run the query, and it does not need your data rows to leave the machine. A tool built for this reads the structure, translates the logic into plain language, and stops there; running anything that changes data is a separate, deliberate act behind a confirmation, not a side effect of asking “what does this do?”

That is where SQL Sage fits. It is an AI copilot inside the editor you already use — an add-in for SQL Server Management Studio and a plugin for DBeaver — that explains, translates, and optimizes SQL grounded in your real schema. It stays read-only by default, sends only your schema and SQL text to the model (never your data rows, unless you opt in per session), and is keyless: you sign in with your own Claude or ChatGPT account, so there is no vendor in the data path. For making sense of an inherited query, that is the whole point — it reads the structure and explains it, without running anything or shipping your data anywhere. You can see it and the DBeaver sibling on the SQL Sage products page.

The takeaway

An inherited query is intimidating because it arrives as one wall of text, but it was built out of small, understandable pieces, and you can take it apart the same way:

  1. Format it first — make the structure visible before you read a word of logic.
  2. Find the point — read the final SELECT to learn what the query is for, remembering the engine evaluates FROM long before SELECT.
  3. Name every block — read each CTE and subquery in isolation as a temporary table, and write down what it returns.
  4. Map the aliases — keep a running table of alias to real table; it catches self-joins and shadowed names.
  5. Check it against the schema — the query’s assumptions are hypotheses; confirm them against the real database rather than trusting them.

Do those five things and a 200-line query stops being a wall and becomes what it always was: a handful of labelled parts, joined. You don’t have to run it to read it, and you don’t have to guess at it when the schema is right there to check.

SQL Sage is made by LumaSoft (LUMA sp. z o.o.) and is not affiliated with Microsoft, Anthropic, OpenAI, or DBeaver.

← Back to the blog