← Lessons

quiz vs the machine

Platinum1800

Databases

Query Rewrite Rules

Transformations that reshape a query into an equivalent faster form.

5 min read · advanced · beat Platinum to climb

Query Rewrite Rules

Query rewrite rules transform a query into a logically equivalent form that may run faster. They reshape the plan before cost based search, often unlocking better physical choices.

Common rewrites

Optimizers apply many algebraic rules:

  • Predicate pushdown moves filters toward scans.
  • Subquery unnesting turns a correlated subquery into a join, which optimizes far better.
  • Constant folding evaluates expressions like one plus one once.
  • Join elimination drops a join whose table contributes no needed columns and cannot change row counts.

Each rule must preserve the result exactly, so they rely on relational algebra equivalences.

Rule based versus cost based

Some rewrites always help and are applied unconditionally. Others are explored as alternatives and judged by the cost based optimizer, since whether they help depends on the data.

Key idea

Query rewrite rules transform a query into equivalent forms, applying sure wins outright and letting the cost optimizer judge the rest.

Check yourself

Answer to earn rating on the learn ladder.

1. What must every query rewrite rule guarantee?

2. Why is subquery unnesting valuable?

3. How are uncertain rewrites decided?