Rewrite a Relational Plan: Sink Filters and Trim Columns
Trees & GraphsModel answerLast updated
Transform a tree of Scan, Filter, Project and Join operators by moving filters toward the leaves and removing unused columns, while keeping query results unchanged.
Rewriting a Relational Query Plan
A query engine stores a plan as a tree of operators. Four operator kinds exist:
Scan(table_name, columns): a leaf that reads a table and exposes the listed columns.Filter(predicate, child): keeps only rows that satisfy the predicate.Project(columns, child): keeps only the listed columns.Join(condition, left, right): an inner join of two inputs. It is the only node with two children.
The node class is:
class Node:
def __init__(self, type, children=None, **kwargs):
self.type = type
self.children = children or []
self.kwargs = kwargs # columns, predicate, condition, table_name, ...
Task
Write optimize_plan(root) that returns the root of an equivalent but cheaper plan, by applying two rewrites in order:
- Predicate pushdown. If a
Filtersits above aJoinand its predicate only mentions columns from one join input, move the filter into that input, and keep sinking it as deep as is legal. - Projection pruning. Going from the root toward the leaves, drop every column that no ancestor outputs and no operator on the way (filter predicate, join condition) evaluates.
Example
Project([a, b],
Filter(a > 10,
Join(c == d,
Scan(T1, [a, c]),
Scan(T2, [b, d]))))
Column a exists only in T1, so after optimization the filter must be applied on the T1 side, below the join. Columns c and d are needed by the join condition, so they must survive down to the scans.
Assumptions
- Column names are globally unique across tables.
- A predicate or condition is a short string such as
"a > 10"; the columns it references can be extracted by tokenizing identifiers. - The result must produce exactly the same rows and columns as the input plan.
What to deliver
Describe your approach, justify why each rewrite preserves results, give the complexity, list the edge cases you handle, and write the code.
Hints
Hint 1
Start with a helper that computes the output columns of any node: Scan and Project give their own list, Filter passes through its child's columns, Join concatenates left and right.
Hint 2
For pushdown, recurse into the children first, then, at each Filter, try to sink it: into the left input if its columns are a subset of the left schema, into the right input if a subset of the right schema, through another Filter freely, and through a Project only if the projection keeps every column the predicate needs. Otherwise leave it where it is.
Hint 3
For pruning, carry a 'required columns' set down from the root. Each Filter adds its predicate's columns, each Join adds its condition's columns, each Project narrows the set to its own list. At a Scan, keep only required columns. Run pushdown first so pruning sees filters in their final positions.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both rewrites are standard rule-based optimizer passes over an operator tree. They share one helper: the output schema of a node.
ScanandProject: theircolumns.Filter: its child's schema.Join: left schema followed by right schema.
A second helper, refs(expr), extracts column names from a predicate or condition string. It must strip string literals (so name = 'bob' does not yield bob) and ignore keywords such as AND, OR, NOT, NULL.
Pass 1: predicate pushdown
Process the tree bottom-up. After the children are optimized, handle a Filter by trying to sink its predicate into the child:
| Child type | Action |
|---|---|
Join | If refs(pred) is a subset of the left schema, sink into the left input; if a subset of the right schema, sink into the right; otherwise stop above the join. |
Filter | Filters commute, so keep sinking below it. |
Project | Sink only if the projection retains every column the predicate uses. |
Scan or anything else | Stop and place the filter directly above it. |
An improvement strong candidates mention: split the predicate on top-level AND. For a > 10 AND b < 5 above a join of T1(a) and T2(b), neither whole predicate fits one side, but each conjunct does, and each can be sunk independently.
Pass 2: projection pruning
Walk top-down with a required set, initially the root's full output schema (or the root Project's list).
Project(cols): the child needsrequired ∩ colsplus nothing else from this node; narrowrequiredaccordingly and recurse.Filter: child requiresrequired ∪ refs(pred).Join: both inputs are givenrequired ∪ refs(condition); each input then keeps only what it actually owns.Scan: keep only columns inrequired.
Where a join input would still emit columns no one needs, insert a Project, since joins are where data movement is expensive. Remove any Project that has become a no-op (its list equals its child's schema).
Why it is correct
- Below a join. If
ponly touches left-side columns,σ_p(L ⋈ R) = σ_p(L) ⋈ R, because each output row's left values come from exactly one left row. This holds for inner joins only. With outer joins, filtering the null-supplying side early changes results. - Below a filter.
σ_p(σ_q(X)) = σ_q(σ_p(X)). - Below a project. If
puses only retained columns,σ_p(π_C(X)) = π_C(σ_p(X)). - Splitting on AND.
σ_{p∧q} = σ_p ∘ σ_q. - Pruning. A column is needed at a node only if an ancestor outputs it or some operator on the path evaluates it.
requiredis exactly that union, so nothing used is discarded. - Pass order. Pushdown first, so pruning sees filters in their final positions. Reversed, pruning could remove a column that a filter would later need.
State the assumption that column names are globally unique; real engines resolve qualified names like T1.a.
Complexity
Let n be the node count, h the height, w the column width.
- Pushdown: each conjunct descends at most
hlevels. With a naive recursiveschema, each check costs O(subtree), giving O(n²) worst case. Memoizing the schema per node (or returning it with each rewritten node) brings it to roughly O(n·h). - Pruning: each node is visited once, with set operations costing O(w), so O(n·w).
- Space: O(h) recursion plus the rewritten tree.
Code
import re
class Node:
def __init__(self, type, children=None, **kwargs):
self.type = type
self.children = children or []
self.kwargs = kwargs
_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
_STRING = re.compile(r"'[^']*'")
_KW = {"AND", "OR", "NOT", "NULL", "IS", "IN", "LIKE", "TRUE", "FALSE"}
def refs(expr):
expr = _STRING.sub("", expr or "")
return {t for t in _IDENT.findall(expr) if t.upper() not in _KW}
def conjuncts(pred):
return [p.strip() for p in re.split(r"\s+AND\s+", pred, flags=re.I) if p.strip()]
def schema(n):
if n.type in ("Scan", "Project"):
return list(n.kwargs["columns"])
if n.type == "Filter":
return schema(n.children[0])
if n.type == "Join":
return schema(n.children[0]) + schema(n.children[1])
raise ValueError(n.type)
def place(pred, cols, n):
if n.type == "Join":
l, r = n.children
if cols <= set(schema(l)):
return Node("Join", [place(pred, cols, l), r], **n.kwargs)
if cols <= set(schema(r)):
return Node("Join", [l, place(pred, cols, r)], **n.kwargs)
elif n.type == "Filter":
return Node("Filter", [place(pred, cols, n.children[0])], **n.kwargs)
elif n.type == "Project" and cols <= set(n.kwargs["columns"]):
return Node("Project", [place(pred, cols, n.children[0])], **n.kwargs)
return Node("Filter", [n], predicate=pred)
def push_down(n):
kids = [push_down(c) for c in n.children]
if n.type != "Filter":
return Node(n.type, kids, **n.kwargs)
out = kids[0]
for p in conjuncts(n.kwargs["predicate"]):
out = place(p, refs(p), out)
return out
def prune(n, required):
t = n.type
if t == "Scan":
cols = [c for c in n.kwargs["columns"] if c in required]
kw = dict(n.kwargs); kw["columns"] = cols
return Node("Scan", [], **kw)
if t == "Filter":
need = required | refs(n.kwargs["predicate"])
child = prune(n.children[0], need)
return Node("Filter", [child], **n.kwargs)
if t == "Join":
need = required | refs(n.kwargs["condition"])
l = prune(n.children[0], need)
r = prune(n.children[1], need)
return Node("Join", [l, r], **n.kwargs)
if t == "Project":
cols = [c for c in n.kwargs["columns"] if c in required]
child = prune(n.children[0], set(cols))
if cols == schema(child):
return child # no-op project
return Node("Project", [child], columns=cols)
raise ValueError(t)
def optimize_plan(root):
if root is None:
return None
root = push_down(root)
return prune(root, set(schema(root)))
Note that the root-level Project passes required equal to the full output, so it is preserved if it actually removes columns.
Edge cases and common mistakes
root is None: returnNone.- A predicate referencing both join sides stays above the join.
- A predicate with no columns (
1 = 1) is a subset of either side; pushing it is harmless. - Treating string literals or keywords as columns produces wrong pushdown decisions.
BETWEEN x AND yis broken by a naiveANDsplit; mention that a real parser avoids this.- A query needing no columns from a table (such as
COUNT(*)) leaves aScanwith an empty column list; real engines still read row counts. - Pruning before pushdown, which can drop a column a filter later needs.
- Pushing through outer joins, which changes results.
- Mutating the input tree in place instead of building new nodes, which makes bugs hard to trace.