Why Great Systems Start by Respecting Invisible Order
Hatched by Kai Nguyen
Jun 09, 2026
9 min read
1 views
84%
The hidden law behind both graphs and queries
What do a topological sort and an optimized SQL query have in common? At first glance, almost nothing. One belongs to graph theory, the other to database performance. But both are ultimately about the same deeper problem: how to do work in the right order when some things depend on other things.
That sounds simple until you realize how often systems fail because they ignore order. A graph with dependencies cannot be flattened arbitrarily. A database cannot be made fast by adding clever syntax after the fact. In both cases, the system rewards those who respect the shape of the problem rather than those who merely apply tools mechanically.
The surprising insight is this: performance is often a consequence of ordering, not effort. When we understand which steps must happen first, which can be delayed, and which should be avoided entirely, we unlock both correctness and speed.
Dependency is the real structure, not the data itself
In a dependency graph, a node with no incoming edges is a source. It can be processed first because nothing must happen before it. A node with only incoming edges and no outgoing edges is a sink. It is the end of a chain, something that depends on others but does not enable anything else.
That is not just a graph concept. It is a universal pattern in complex work.
Think about a software pipeline. You cannot deploy code before it compiles. You cannot compile before dependencies are installed. You cannot install dependencies before the environment exists. The system has a natural order, and pretending otherwise creates friction. Topological sort is simply the formal recognition of that hidden structure.
SQL optimization works by the same logic. A query is not just a sentence that the database reads from left to right. It is a sequence of logical stages, and the cost of each stage depends on whether the database can narrow the work early. If you force the engine to examine too many rows, sort too much data, or compute too many expressions, you are effectively ignoring the dependency structure of the operation.
The fastest system is rarely the one that works hardest. It is the one that does the least impossible work first.
This is why filtering early matters so much. A WHERE clause that sharply reduces the dataset is like identifying the sources in a graph. It shrinks the problem before the expensive parts begin. Once you see this, optimization stops feeling like a bag of tricks and starts looking like a discipline of respecting order.
The deepest mistake: treating every step as equally available
Most inefficiency comes from a false belief: that all operations are equally available at all times.
In graph problems, that mistake produces cycles, dead ends, or algorithms that search blindly instead of following dependencies. In SQL, it shows up when we wrap indexed columns in functions, apply arithmetic to them, or use leading wildcards that prevent index use. The database loses its ability to take a shortcut because we have obscured the natural shape of the data.
Consider the difference between these two conditions:
WHERE age = 30
and
WHERE age + 1 = 31
They are logically equivalent, but not operationally equivalent. The first allows the database to use an index on age. The second often forces it to compute the expression row by row. The database knows the answer, but it cannot reach it efficiently because we hid the dependency behind arithmetic.
This is exactly what happens when a graph algorithm ignores sources and sinks. If you do not start with nodes that are ready, you waste time revisiting nodes that are not yet processable. Topological sort works because it only processes nodes whose dependencies have already been satisfied. That is not just a convenient technique. It is a model of intelligence: only act when the prerequisites are complete.
A useful mental model is to imagine a factory assembly line. Some parts can be bolted together immediately, while others must wait for paint to dry, for a component to be machined, or for a previous stage to finish. The factory does not become faster by trying to do every step at once. It becomes faster by identifying the true bottlenecks and sequencing them correctly.
SQL optimization is the same factory logic. Every extra calculation, sort, or grouping step is a station on the line. If you can reduce the number of items reaching that station, the whole pipeline speeds up.
SARGability is a form of topological thinking
SARGable means a query can use an index effectively. That is a technical term, but the underlying idea is profound: the database can navigate directly to relevant rows instead of scanning everything.
This is not unlike traversing a graph in an order that respects dependencies. In a topological sort, you do not inspect nodes randomly. You choose nodes whose incoming edges have already been cleared, because that is what makes progress possible. An index works similarly. It lets the database move from the general space of all rows to the specific rows that matter, without touching everything in between.
When you apply a function to an indexed column in the WHERE clause, you often destroy that navigation path. For example, if the column is wrapped in LOWER(), DATE(), or arithmetic, the index may no longer help. The engine cannot easily reason backward from the transformed value to the original position in the index.
That is the same cognitive error as taking a dependency graph and erasing the arrows. Once the direction is lost, the structure becomes harder to exploit.
Here is the broader lesson: optimization is not only about faster execution, it is about preserving the machine's ability to reason about structure.
This is why unnecessary sorting and grouping are expensive. Sorting says, in effect, “First, arrange everything into order before deciding what matters.” But if your business question only needs the top 10 rows, or only rows matching a narrow condition, then sorting the entire universe is wasted motion. Topological sort teaches the opposite principle: do not impose a total order until a partial order is enough.
That insight matters outside databases too. Many teams create heavy processes because they confuse standardization with usefulness. They insist on sequence where sequence is not needed. They sort, group, and normalize too early. The result is a system that feels disciplined but behaves sluggishly.
The power of removing work before you do it
The most elegant optimization is often subtraction.
In graph terms, a source is powerful because it is ready. A sink is useful because it marks completion. In SQL terms, a selective WHERE clause is powerful because it reduces the size of every later operation. In both cases, the best move is often to identify the smallest set of things that must be handled and let everything else disappear from the critical path.
This suggests a practical framework for thinking about complex systems:
- Find the sources: What can be processed immediately?
- Find the sinks: What is merely a terminal result, not a dependency for further work?
- Protect the access path: Can the system still use indexes, cached structures, or natural ordering?
- Filter before you transform: Can you reduce the dataset before applying expensive operations?
- Avoid hiding structure: Are arithmetic operations, negations, or leading wildcards obscuring what the engine needs to know?
This framework applies whether you are designing a query, a workflow, or a build system. The question is always the same: what can be resolved upstream so downstream work becomes trivial?
Imagine a librarian asked to find every book in a city that mentions a specific phrase. If the search is done by opening each book page by page, the task is absurdly expensive. If the library has an index, the search becomes precise. But if the phrase is buried inside a transformation, like reversed text or encoded content, the index loses value. That is what happens when we ignore SARGability. We build the right tool, then make it unusable by changing the shape of the question.
Topological reasoning teaches us to keep the question aligned with the structure of the world. SQL optimization teaches us to keep the query aligned with the structure of the data.
A better mental model: respect the shape, then accelerate
Many people think optimization is about cleverness. In reality, it is about alignment.
A graph has a shape. A dataset has a shape. A query has a shape. The job of the engineer is not to overpower that shape, but to reveal it. Once the shape is visible, efficiency follows naturally.
This is why the same discipline helps in both algorithm design and database tuning. In a dependency graph, you ask, “What is ready now?” In SQL, you ask, “What can the engine locate now without scanning?” In both cases, you are trying to preserve directness.
The strongest systems do not ask the machine to guess. They make the path obvious.
Clarity is a performance feature.
That sentence sounds philosophical, but it is deeply practical. A query that keeps indexed columns bare is clearer to the database. A topological ordering that starts from sources is clearer to the algorithm. A workflow that exposes dependencies is clearer to the team. Clarity reduces search space, and reduced search space is the foundation of speed.
So if your code is slow, do not begin by asking how to make it more powerful. Ask how to make it more honest about the order in which things must happen.
Key Takeaways
- Look for dependencies first. Before optimizing a process, identify what must happen before something else can begin.
- Filter early. Reduce the input set as soon as possible, especially before sorting, grouping, or expensive calculations.
- Keep indexed columns “visible.” Avoid wrapping them in functions, arithmetic, or leading wildcards when you want the database to use indexes.
- Prefer structure over brute force. Whether in graphs or SQL, preserving natural structure is usually faster than compensating for its loss.
- Ask what can be removed. Often the best optimization is not a faster operation, but fewer operations.
Conclusion: speed is a byproduct of respecting order
We often talk about performance as if it comes from more power, more hardware, or more clever code. But the deeper truth is quieter and more interesting: speed comes from understanding what the system already knows about itself.
A topological sort respects the direction of dependency. A good SQL query respects the engine's ability to find rows efficiently. Both are examples of a larger principle: when you stop fighting the structure of a problem and start cooperating with it, work becomes simpler, faster, and more reliable.
The real question is not, “How do I make this run faster?” The better question is, “What order does this problem want?” Once you can answer that, optimization stops being a trick and becomes a form of wisdom.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣