Query decomposition is the process of breaking one SQL statement into smaller, self-contained pieces that can be pushed to different nodes, then combined into a single result. You do it to cut network traffic, avoid dragging whole tables across the network, and let each node work on the slice it owns. The shortest working version is: parse the query, normalise it into a canonical form, flatten nested subqueries and views, push selections and projections down toward the data, rewrite the remaining operations into relational algebra, then add a note about where each fragment will run. Everything below happens on paper or inside the optimiser — you are not editing data, so the process is safe to repeat.

A note on terminology: many distributed systems (PostgreSQL with Citus or postgres_fdw, CockroachDB, TiDB, Vitess, YugabyteDB, MongoDB sharded clusters, and most data warehouses) do this automatically in their planner. You do the decomposition manually when you are tuning a slow query, writing a federated query across heterogeneous sources, designing a sharded schema, or studying how your engine thinks. Menu labels and function names differ by engine version and region, so treat the steps as a method rather than a click path.

What You'll Need

  • The full query text, ideally with EXPLAIN output from your engine so you can see what the planner already does.
  • A simple schema diagram showing which tables live on which node, and which column is the distribution or shard key.
  • Read access to the system catalogs or the metadata service so you can confirm where each table actually sits.
  • A place to record the decomposition — a text file or notebook with the original query, the algebra, and the fragment plan.
  • Familiarity with relational algebra basics: selection (σ), projection (π), join (⋈), union (∪).
  • Optional but useful: a staging environment with a copy of the data so you can compare the rewritten fragments against the original result.

Step-by-Step

  1. Write down the original query exactly as it runs. Copy it without reformatting. Note the client, the engine, and whether the query crosses schemas or databases. This is your reference answer — every later step must return the same rows.
  2. Parse and sanity-check the syntax. Confirm every table and column exists and that the query is valid on the coordinator. Fix typos and ambiguous column names first; they cost nothing and confuse every later step. A query that fails to parse on one node will fail everywhere.
  3. Normalise the query into a canonical form. Rewrite it so identical predicates look identical: use consistent capitalisation, expand SELECT * into an explicit column list, replace BETWEEN with >= and <= where that is clearer, and turn NOT (a = b) into a <> b. Normalisation makes duplicate and contradictory predicates visible — for example a filter demanding region = 'EU' and region = 'US' on the same row, which is empty and can be discarded before anything travels.
  4. Analyse the query tree. Sketch the parse tree with operations as nodes and tables as leaves. Mark each leaf with the node name that stores that table. You are looking for the first point where data from two different nodes must meet.
  5. Flatten subqueries, views and nested selects. Wherever a view or a simple subquery sits in the FROM clause, substitute the underlying tables and merge the predicates — the optimiser term is view merging or subquery flattening. Only correlated subqueries and aggregates need to stay as separate blocks. Flattening exposes filters that would otherwise sit above a join, which is where they do the most network damage.
  6. Convert to relational algebra. Rewrite the query as a sequence of σ (select), π (project), ⋈ (join), ∪ (union) and grouping operations. Keep the column names visible at every step. This is the form you can legally reorder in the next steps; SQL text is too rigid to push around safely.
  7. Push selections down. Move every predicate that references only one table's columns as close to that table as possible, so the filter runs where the data lives. A predicate like orders.created_at > '2026-01-01' travels to the orders node; only the surviving rows cross the network. Predicates that reference two tables cannot be pushed and must wait for the join.
  8. Push projections down. Trim each fragment to the columns it actually needs, including join keys. Dropping unused wide columns cuts transfer size immediately and is one of the cheapest wins in the entire process.
  9. Identify join strategy per join. For each join, look at where the two tables live. If one side is small and local to the coordinator, consider shipping it whole to the larger table (a broadcast or bind join). If both sides are large and unsharded on the join key, the join will need a shuffle or a repartition — note that explicitly, because it is the expensive part of your plan.
  10. Group the operations into fragments. Bundle each contiguous block of work that runs on one node into a fragment, label it with its destination node, and record what it returns. Typically you get one fragment per base table plus a coordinator fragment that joins and aggregates the partial results.
  11. Define the assembly step. For aggregates, decide how the partial results combine: SUM and COUNT add, MIN and MAX take the extreme, but AVG must be decomposed into SUM and COUNT per fragment and divided at the end. For DISTINCT, deduplicate after the union, not before.
  12. Check the rewriting rules. Confirm that commuting selection with join and projection with join preserved semantics: pushing a filter through an outer join can change which rows survive as nulls. The same applies to pushing predicates across UNION and LEFT JOIN. If a rule does not apply safely, leave the operation where it is.
  13. Validate on data. Run the original and the fragment plan in staging and compare row counts and a checksum (COUNT(*) plus a SUM over a numeric key is usually enough). Any mismatch points to a predicate pushed where it should not have been.
  14. Record the result as a plan. Save the algebra, the fragment map, and the assembly rules next to the query in your documentation. Next time you tune a similar query, you start from this plan rather than from the SQL text.

Common Mistakes

  • Pushing predicates through outer joins. A filter on the outer (nullable) side can turn matched rows into dropped rows. Keep such predicates above the join.
  • Shuffling before filtering. If a predicate is legal to push but you leave it above a join, the network carries every row instead of the relevant ones — often the whole difference between a fast query and an unusable one.
  • Forgetting that aggregates do not all combine. Averaging per-fragment averages gives the wrong answer when fragment sizes differ; always carry sums and counts and divide once.
  • Ignoring the join key versus the shard key. Two large tables sharded on different columns force a repartition. Decomposition cannot fix that; only a schema or query change can.
  • Dropping join columns during projection. Trimming columns too aggressively breaks the join at the coordinator step. Carry every join key and every column used in a later predicate.
  • Treating a correlated subquery as independent. It cannot be pushed as one fragment because it needs the outer row each time; either rewrite it as a join or plan an explicit per-row round trip.
  • Skipping the validation step. Rewrites look correct on paper far more often than they are correct on data.

Tips

  • Start decomposition from the WHERE clause, not from the SELECT list. Filters drive everything else.
  • Use EXPLAIN (and EXPLAIN ANALYZE where your engine supports it) as a feedback loop: your manual fragments should roughly match what the planner already pushes down. Where they differ, the planner is usually right — learn why.
  • Measure transfer, not just time. Decompositions that reduce rows moving between nodes usually win even if local CPU goes up slightly.
  • Keep the rewritten fragments readable and commented with the node they target; plan documents rot quickly otherwise.
  • Design queries so the join key and the shard key agree. Co-located joins avoid the shuffle entirely.
  • For federated queries across engines, push as much as each source can run natively, then assemble the smallest possible intermediate result centrally.

Troubleshooting

The rewritten query returns different rows. Undo the last pushdown and test again. Outer joins, UNION ALL versus UNION, and null handling in predicates are the usual suspects.

Aggregates come back wrong. Recheck the assembly rule. Averaging, combining DISTINCT counts, and mixing nullable columns in COUNT all break naive combination.

The decomposed version is slower. Check whether you introduced a shuffle where a broadcast would have done, or whether you removed a filter the planner was pushing for you. Compare EXPLAIN output of both versions before and after.

A fragment fails on a remote node. Run it there directly. The usual causes are missing tables or permissions on that node, a schema that differs slightly, or a data-type mismatch across engines. Fix the fragment in place and retry.

Results are inconsistent between runs. Your query may be reading data that is being written concurrently, or one fragment may hit a replica that is behind. Confirm the read consistency settings before assuming your rewriting is wrong.

Frequently Asked Questions

Do I have to decompose queries by hand in a distributed database?

No. Most distributed engines do it in the planner automatically. Manual decomposition is for tuning, teaching, federated queries across separate systems, and cases where the planner's choice is poor.

What is the difference between decomposition and optimisation?

Decomposition restructures the query into correct fragments; optimisation chooses among alternative fragment plans — which side of a join to ship, which join order, which node does the final merge.

Can every query be decomposed cleanly?

No. Correlated subqueries, joins on non-shard keys between large tables, and some recursive queries resist clean decomposition and force data movement or a different schema.

Why not just broadcast the whole small table?

Broadcasting multiplies transfer by the number of nodes. It is fine for genuinely small tables and wasteful for medium ones; the crossover depends on table size and node count, so measure rather than guess.

How do I verify a decomposition is correct?

Compare row counts and a checksum against the original query on the same data snapshot. If they match on several representative filter values, the rewrite is usually sound.

Does this apply to NoSQL as well?

The same principles apply — filter and project at the shard, minimise what crosses the network, combine partial results carefully — though the operations are expressed in the engine's own query language rather than relational algebra.