Inferensys

Glossary

Query Rewriting

Query rewriting is a query optimization technique that transforms an input query into a semantically equivalent but more efficient form before execution plan creation.
Stylish home-office setup in a modern highrise apartment, floor-to-ceiling windows showing city skyline at golden hour, a laptop displaying a beautiful semantic search interface.
GRAPH QUERY OPTIMIZATION

What is Query Rewriting?

Query rewriting is a foundational optimization technique in database and knowledge graph systems that transforms an input query into a semantically equivalent but more efficient form before execution planning.

Query rewriting is a query optimization technique that transforms an input query into a semantically equivalent but more efficient form before the creation of an execution plan. It operates on the logical representation of a query, applying algebraic transformations and rule-based heuristics to simplify its structure. This process, often a precursor to cost-based optimization (CBO), aims to reduce computational complexity by eliminating redundancies, pushing down filters, and leveraging known constraints like integrity rules or materialized views.

In graph databases and knowledge graphs, rewriting is crucial for optimizing complex pattern-matching queries expressed in languages like Cypher, SPARQL, or Gremlin. Techniques include rewriting subqueries as joins, eliminating redundant traversals, and substituting patterns with precomputed results from materialized views. The goal is to produce a query that, while returning identical results, requires fewer computational resources—less I/O, reduced intermediate result sizes, and lower overall latency—when processed by the underlying engine.

GRAPH QUERY OPTIMIZATION

Core Query Rewriting Techniques

Query rewriting transforms an input query into a semantically equivalent but more efficient form before execution plan generation. These techniques are foundational for optimizing complex graph pattern matching.

01

Predicate Pushdown

Predicate pushdown is a fundamental rewriting rule that moves filtering conditions as close as possible to the data source. In graph queries, this means applying node or edge property filters during the initial traversal or scan, drastically reducing the size of intermediate result sets passed to subsequent operations like joins.

  • Example: A query to find (p:Person)-[:WORKS_AT]->(c:Company) where c.name = 'Inferensys' is rewritten to scan only for Company nodes with that name first, before performing the expansive WORKS_AT traversal.
  • Impact: Minimizes I/O and memory usage by eliminating non-matching data early in the pipeline.
02

View Unfolding / Inlining

View unfolding replaces a reference to a predefined view or named subquery with its underlying definition. This allows the optimizer to apply global transformations—like predicate pushdown or join reordering—across the entire expanded query, rather than treating the view as a black box.

  • Use Case: A view SeniorEmployees defined as MATCH (p:Person) WHERE p.years_exp > 10 RETURN p is inlined into a larger query. The optimizer can then push a predicate like p.department = 'Engineering' directly into the view's scan.
  • Benefit: Enables holistic optimization that can reveal redundant operations or more efficient join paths.
03

Join Reordering & Factorization

This technique rewrites the order and structure of joins (or graph pattern matches) to minimize the computational cost. Join reordering sequences patterns to produce the smallest intermediate results first. Common subexpression factorization identifies and computes duplicate sub-patterns once, caching the result for reuse.

  • Graph Example: A query matching (a)-[:KNOWS]->(b), (a)-[:WORKS_WITH]->(c), (b)-[:KNOWS]->(c) might be reordered to find the smallest KNOWS subgraph first.
  • Optimization Goal: Reduces the combinatorial explosion inherent in matching multi-hop graph patterns, which is critical for cost-based optimization.
04

Query Decorrelation

Decorrelation transforms a nested subquery (e.g., a correlated subquery that executes once for each row of an outer query) into an equivalent, non-nested form using joins or semi-joins. This removes iterative execution, allowing for set-based, parallel processing.

  • SPARQL/Cypher Context: A OPTIONAL or EXISTS sub-pattern that references variables from an outer match is rewritten into a left-outer-join or an anti-join.
  • Performance Impact: Eliminates the performance penalty of repeated subquery execution, often resulting in orders-of-magnitude speedups for complex existential checks.
05

Constant Folding & Propagation

Constant folding evaluates expressions composed solely of constants at compile time (e.g., rewriting WHERE age > 18+2 to WHERE age > 20). Constant propagation then pushes these known values through the query, potentially simplifying other expressions or enabling more aggressive predicate pushdown.

  • Graph Application: Propagating a constant node ID or unique property value can allow the optimizer to select a highly efficient direct lookup or index scan instead of a full label scan.
  • Benefit: Reduces runtime computation overhead and provides the optimizer with more concrete information for plan selection.
06

Elimination of Redundant Operations

This class of rewrites removes operations that do not affect the final query result. This includes eliminating duplicate predicates, removing unnecessary DISTINCT operators when uniqueness is guaranteed by constraints, and pruning unreachable query branches based on contradictory conditions.

  • Example: A WHERE clause with p.name = 'Alice' AND p.name = 'Alice' has the duplicate removed. A MATCH for a node with two mutually exclusive labels is simplified.
  • Goal: Streamlines the logical query plan, reducing both compilation and execution overhead for cleaner, faster plans.
GRAPH QUERY OPTIMIZATION

How Query Rewriting Works in Graph Databases

Query rewriting is a foundational optimization technique that transforms an input query into a semantically equivalent but more efficient form before execution planning begins.

Query rewriting is a logical optimization technique that transforms a declarative graph query into a semantically equivalent form that is more efficient to execute. It applies a set of deterministic rules based on logical algebra and graph pattern semantics, such as eliminating redundant operations, pushing filters earlier in the logical plan, or unnesting complex subqueries. This process occurs before cost-based optimization (CBO) and is independent of specific data statistics, focusing purely on the query's structure to reduce computational complexity.

In graph databases, rewriting is crucial for optimizing complex graph pattern matching and traversal queries. For a query like MATCH (a)-[:KNOWS*2..3]->(b) WHERE a.name = 'Alice', a rewriter might push the property filter on node a to the start of the traversal, preventing the exploration of irrelevant paths. This technique directly reduces the size of intermediate results, which is critical for performance in subgraph isomorphism problems. Effective rewriting lays the groundwork for the physical optimizer to select optimal indexes and join orders.

GRAPH QUERY OPTIMIZATION

Query Rewriting in Database Systems

Query rewriting is a foundational query optimization technique that transforms an input query into a semantically equivalent but more efficient form before the creation of an execution plan. It applies logical transformations based on rules, heuristics, and algebraic properties.

01

Logical vs. Physical Optimization

Query rewriting is a logical optimization phase. It operates on the high-level, declarative query structure (e.g., an abstract syntax tree or relational algebra expression) before a cost-based optimizer translates it into a physical execution plan with specific algorithms (e.g., hash join vs. merge join) and access methods.

  • Logical Transformations: Include pushing filters down, eliminating redundant joins, and simplifying expressions. These are generally cost-independent.
  • Physical Optimization: Follows rewriting and is cost-dependent, selecting specific operators and data structures based on estimated I/O, CPU, and memory usage.
02

Common Rewriting Rules & Heuristics

Rewriters apply a catalog of equivalence-preserving rules. Key heuristics aim to reduce the size of intermediate results early in the plan.

  • Predicate Pushdown: Move filtering conditions (WHERE, FILTER) as close to the base data scan as possible.
  • Projection Pushdown: Eliminate unused columns early to reduce data volume in pipes.
  • Join Elimination: Remove unnecessary joins where foreign key constraints guarantee the join does not alter cardinality.
  • View Unfolding: Replace a reference to a view with its underlying query definition, enabling further optimization.
  • Constant Folding: Evaluate constant expressions at compile time (e.g., rewrite WHERE price > 10+5 to WHERE price > 15).
03

Graph-Specific Rewriting

In property graph and RDF databases, rewriting leverages graph-specific semantics and pattern matching.

  • Path Pattern Simplification: Collapse linear chains of nodes and relationships into more efficient single-step traversals where possible.

  • Label and Type Filter Pushdown: Push node/edge label filters to the initial scan or traversal operation, leveraging index-free adjacency.

  • SPARQL-to-SQL Rewriting: In RDF triplestores, complex SPARQL queries with OPTIONAL, UNION, and property paths are often rewritten into a series of optimized SQL queries against the underlying triple table or property tables.

04

Interaction with Materialized Views

A powerful application of query rewriting is automatic query rewriting with materialized views. The optimizer recognizes that part or all of a query can be answered by a precomputed materialized view, rewriting the query to scan the view instead of the base tables.

  • This requires view matching, a complex subgraph isomorphism problem, to check if the view's definition is equivalent to, or contains, the query's needs.
  • It dramatically accelerates queries on aggregated or joined data, trading storage for compute time.
05

Semantic Query Optimization

This advanced form of rewriting uses integrity constraints and domain knowledge (e.g., from an ontology) to transform queries. It's central to semantic reasoning engines.

  • Example Using Constraints: If a query asks for Employee and a constraint states Manager SubClassOf Employee, the rewriter can include Manager instances in the result, or rewrite to search the superclass.
  • Inference-Based Rewriting: In a knowledge graph, if :hasParent is defined as transitive, a query for ancestors can be rewritten into a simpler, bounded traversal.
06

Limitations and Trade-offs

While powerful, query rewriting has boundaries.

  • Semantic Equivalence: The rewritten query must produce the exact same result set as the original. Not all faster forms are equivalent.
  • Rule Explosion: The number of possible rewrites can be large. Optimizers use heuristics to prune the search space.
  • Cost Blindness: Pure logical rewriting does not consider data distribution or physical storage. A logically "better" form (e.g., a different join order) may be physically worse, which is why it is followed by cost-based optimization.
  • Complexity with Subqueries and Aggregation: Rewriting nested subqueries and queries with aggregation requires careful handling to preserve grouping and scoping rules.
QUERY REWRITING

Frequently Asked Questions

Query rewriting is a foundational optimization technique in graph databases and knowledge graph systems. It transforms an input query into a semantically equivalent but more efficient form before execution plan generation, directly impacting performance and cost.

Query rewriting is a query optimization technique that transforms an input query into a semantically equivalent but more efficient form before the creation of an execution plan. It works by applying a set of logical transformations based on the algebraic properties of the query language and the constraints defined in the schema or ontology. The optimizer analyzes the original query's abstract syntax tree (AST) and applies rules—such as predicate pushdown, view unfolding, or join reordering—to produce a new query that will yield the same result but with lower estimated computational cost. This process occurs in the logical optimization phase, separate from physical plan generation which deals with access methods and algorithms.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.