Why the Best Queries Think Like Graph Algorithms

Kai Nguyen

Hatched by Kai Nguyen

May 14, 2026

9 min read

84%

0

The hidden similarity between dependencies and data

What do a build pipeline, a corporate org chart, and a SQL report have in common? More than most people realize: each one is really a question about order.

If you have tasks that depend on other tasks, you cannot just arrange them arbitrarily. If you have records that belong to groups, you cannot interpret a rank until you first define the group. In both cases, the real problem is not calculation. It is finding the correct structure before applying the calculation.

That is the deeper connection between topological sort and SQL windowing. One helps you respect dependencies. The other helps you respect boundaries. Together, they point to a powerful idea: good reasoning systems do not start with answers. They start with constraints.

The hardest part of many problems is not solving them, but discovering the order in which they become solvable.

This is why these two topics belong together. Topological sort asks, “What must happen before what?” SQL partitioning asks, “Which things belong together before we compare them?” Both are about creating a valid frame for computation.


When order matters more than work

At first glance, topological sort looks like a graph trick. But conceptually, it is a discipline of respecting the direction of reality. A source node has no incoming edges because nothing must come before it. A sink node has no outgoing edges because nothing depends on it afterward. In between, every node sits inside a network of prerequisites.

That pattern shows up everywhere. You cannot publish a newsletter before writing it, edit a video before capturing footage, or run a deployment before the tests pass. Any system with prerequisites contains a hidden graph, even if nobody draws it.

This matters because many failures come from trying to do the right work in the wrong order. Teams often ask, “What is the next task?” when the better question is, “What is now eligible to be done?” That is a topological mindset. It turns project management from wishful sequencing into dependency-aware reasoning.

A useful mental model is to imagine each task as a locked room. A source node is a room whose door is already open. Every time you finish one room, you may open others. The goal is not to force progress everywhere at once, but to reveal the next feasible step. That is why topological ordering feels elegant: it converts a complex web of constraints into a sequence of legal moves.

Now notice the same logic in SQL. Suppose you want to rank employees within each department. If you rank the entire table without grouping, your result mixes unrelated populations. The calculation is mathematically valid but semantically wrong. The partition by clause is the equivalent of drawing the graph’s boundaries. It tells the database, “These rows belong together. Compute within this universe, not across all universes.”

So the deeper issue is not graph theory versus SQL. It is global versus local meaning. A result only makes sense when you know which constraints define its context.


Partitions are the SQL version of dependency awareness

Window functions are often taught as a convenience feature, but they are more profound than that. They let you compute values while preserving the original rows, which means you can ask relational questions without collapsing the data too early. That is a subtle but important distinction.

Consider ranking salespeople by revenue within each region. The key insight is that the same numeric value can mean different things depending on the group. A revenue of 500,000 may be excellent in one region and average in another. Partitioning gives the value a proper frame of reference.

This is not so different from a graph with multiple chains of dependencies. Imagine product release steps across separate teams. The QA workflow for one feature may be independent of the documentation workflow for another, even if both happen on the same calendar. If you ignore the structure, you will create false comparisons. If you respect it, each chain can be evaluated on its own terms.

Here is the common thread: both tools prevent category mistakes.

A category mistake happens when you compare things that live in different logical spaces. Topological sort prevents you from scheduling a dependent task too early. partition by prevents you from ranking a row against the wrong peer group. In both cases, the structure is not decorative. It determines what the output even means.

This is why SQL window functions feel so empowering to people who are new to them. They reveal that aggregation is not the only way to reason about data. You do not always need to compress the table into one row per group. Sometimes the right move is to keep the full table visible, but impose a local lens through which the computation operates.

That local lens is philosophically close to topological sort. A topological ordering does not pretend the graph has no complexity. It simply respects the fact that some nodes are not ready until others have been resolved. Similarly, a window function does not flatten all rows into one undifferentiated mass. It computes within a context that preserves meaning.

Structure is not an extra layer on top of data or tasks. Structure is what makes the data or task interpretable in the first place.


A better framework: first define the universe, then compute inside it

The cleanest way to unify these ideas is to use a two step framework.

1. Identify the universe of comparison

Before doing any calculation, ask: what belongs together?

In graph terms, this means identifying the dependency subgraph. In SQL terms, it means deciding the partition. In everyday work, it means clarifying the scope of a decision. Are we comparing products within the same category, candidates within the same hiring funnel, or tickets within the same sprint?

Without this step, you risk producing outputs that look precise but are conceptually meaningless.

2. Identify the legal order of operations

Once the universe is defined, ask: what must precede what?

In graphs, that is the topological ordering. In SQL, it is the sequence of transformations that leads to a valid analytic result. You may need to filter first, partition second, rank third, and only then select the top rows. The order of operations is not arbitrary. It determines whether the final result is faithful to the problem.

This framework is surprisingly general. It applies to writing, software architecture, and decision making.

For example, if you are drafting a strategy memo, you do not begin with recommendations. You first establish the scope of the problem, the relevant comparators, and the dependencies among choices. Only then do conclusions become persuasive. That is a topological process disguised as writing.

Likewise, in analytics, people often jump straight to averages or rankings. But averages across mixed groups can conceal more than they reveal. Window functions are useful precisely because they preserve row-level detail while adding local context. They let you avoid the trap of over-aggregating too early, which is the analytical equivalent of trying to topologically sort a graph before identifying its edges.

A useful analogy is city planning. You cannot design traffic flow by looking at every road in the country at once. You first define neighborhoods, routes, and bottlenecks. Then you determine which intersections control movement. A partition is like a neighborhood, and a topological source is like a road segment that can begin traffic flow without waiting for upstream congestion to clear.

The common principle is simple: computation should follow structure, not replace it.


The real skill is learning to see the graph inside the table

Most people treat graphs and tables as different species of data. But many real problems are both. A table of events often hides a process. A process often hides a graph.

A customer journey is a graph of dependencies, because some actions can only happen after others. A SQL table of orders is a sequence of records, but it can be transformed into a ranked view of behavior once you define the right partition. The same raw facts can become either a relational table or a dependency network depending on the question you ask.

This is why strong analytical thinking is not just about knowing more tools. It is about seeing the same hidden property in different forms. When you ask, “What is upstream of this?” you are thinking like a graph algorithm. When you ask, “What is the right peer group?” you are thinking like a window function. Both questions reduce confusion before computation begins.

There is also a practical payoff: this mindset helps you debug bad outputs faster.

If a topological ordering seems impossible, you know to look for a cycle, meaning a circular dependency. If a ranked SQL result looks wrong, you know to check the partition boundaries, sort order, and frame definition. In both cases, the issue is usually not the core arithmetic. It is a hidden structural assumption.

That makes these techniques more than technical patterns. They are diagnostic habits.

Ask of every problem:

  • What are the dependencies?
  • What are the peer groups?
  • What must be settled before something else becomes meaningful?
  • What would make a result comparable rather than merely calculated?

These questions turn vague complexity into an analyzable structure.


Key Takeaways

  1. Order is part of the problem, not just the solution. In both graphs and SQL, correct results depend on sequencing and scope.

  2. Partitioning is conceptual, not just technical. A partition by clause defines the universe in which a metric is meaningful.

  3. Topological thinking prevents premature action. A valid dependency order tells you what can be done now versus what must wait.

  4. Many bad analytics come from mixing groups too early. Ranking, averaging, or comparing across incompatible populations creates false certainty.

  5. Look for structure before computation. Whether you are writing code, analyzing data, or planning work, first identify the dependencies and boundaries, then calculate inside them.


Conclusion: the best answers are context aware

The deepest lesson here is not that graphs and SQL are similar in a technical sense. It is that both teach the same intellectual discipline: do not compute before you know the rules of the world you are computing in.

Topological sort respects the fact that some truths depend on earlier truths. Window functions respect the fact that some comparisons only make sense within a local context. Together, they reveal a broader principle of reasoning: clarity comes from honoring structure before chasing outputs.

That reframes expertise in a useful way. The expert is not the person who calculates fastest. The expert is the person who can see when a problem is really about dependency, when it is really about grouping, and when both are true at once.

In that sense, the best queries do not just ask for an answer. They ask for the right universe in which an answer can exist.

Sources

← Back to Library

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 🐣