> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pawsql.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> PawSQL 是一个产品：Cloud 是公网部署形态，Engine / Optimizer / Auditor / Advisor / Patroller 是同一产品的组件与交付形态，不是彼此独立的产品。 / PawSQL is a single product: Cloud is the public deployment form, while Engine / Optimizer / Auditor / Advisor / Patroller are components and delivery forms of the same product, not separate products.
> 术语以站内术语表为准：SQL 审核对应英文 SQL Review，查询重写对应 Query Rewrite，索引推荐对应 Index Recommendation；英文内容统一用 Review，不用 Audit。 / Use the site glossary for terminology: 审核 is SQL Review, 重写 is Query Rewrite, 索引推荐 is Index Recommendation; English content uses Review, never Audit.
> 引用能力范围或版本支持时以对应页面为准；标注 unknown、或 status 非 published 的内容表示尚未经产品核实，不应作为事实引用。 / Cite capability scope and version support from the corresponding page; content marked unknown, or with a status other than published, is not yet product-verified and must not be cited as fact.

# Query Rewrite

> Automatically transform inefficient SQL into semantically equivalent forms that are more optimizer-friendly and performance-oriented.

PawSQL Query Rewrite uses SQL parsing, semantic analysis, and optimization rules to transform inefficient SQL into semantically equivalent forms that give the database optimizer better opportunities to produce efficient execution plans.

Instead of only returning textual recommendations, PawSQL aims to generate executable optimized SQL and then validate whether the rewrite actually improves performance.

## Overview

Many SQL performance problems are caused not by missing indexes, but by SQL structures that restrict the optimizer's available execution strategies.

Common examples include:

* Repeated execution of correlated subqueries
* Predicates that cannot be pushed down
* OR expressions that reduce index usability
* Unnecessary DISTINCT or GROUP BY operations
* Deep pagination that scans and sorts excessive rows
* Cross-shard data movement in distributed databases

Query Rewrite targets these structural issues with equivalent transformations.

```mermaid theme={null}
flowchart LR
    A["Original SQL"] --> B["Parse & Analyze"] --> C["Rewrite Rules"] --> D["Candidate SQL"] --> E["Cost Validation"] --> F["Optimized SQL"]
```

## Why Query Rewrite Matters

A database optimizer searches for the best execution plan within the structure of the SQL statement it receives. It does not always transform the business expression of that SQL into an entirely different but equivalent form.

Semantically equivalent SQL expressions can expose very different optimization opportunities.

PawSQL Query Rewrite expands the search space available to the optimizer.

## Key Capabilities

### Subquery rewrite

Analyze IN, EXISTS, scalar subqueries, and related forms to identify equivalent structures that may execute more efficiently on the target database.

### Predicate optimization

Optimize WHERE and JOIN predicates, including:

* Predicate pushdown
* Redundant predicate elimination
* OR-condition rewrite
* Expression simplification
* Recovery of index-friendly predicates

### Join optimization

Identify and optimize:

* Redundant joins
* Join elimination
* Structural join issues
* Subqueries that can be decorrelated
* Cross-shard join risks in distributed databases

### Aggregation optimization

Rewrite or simplify DISTINCT, GROUP BY, COUNT, MIN/MAX, and related aggregation patterns.

### Pagination optimization

Generate alternative forms for deep OFFSET / LIMIT pagination scenarios.

### Distributed SQL optimization

Consider distributed-database characteristics such as:

* Distribution keys
* Data movement
* Cross-node joins
* Replicated or broadcast tables
* Global and local indexes

### Big data SQL optimization

Analyze big-data SQL patterns such as:

* Partition pruning
* Bucket joins
* Data skew
* COUNT DISTINCT
* GROUP BY skew
* Window-function skew
* Global sorting

## Example

Original SQL:

```sql theme={null}
SELECT *
FROM orders
WHERE customer_id = 100
   OR customer_id = 200
   OR customer_id = 300;
```

Possible equivalent rewrite:

```sql theme={null}
SELECT *
FROM orders
WHERE customer_id IN (100, 200, 300);
```

Whether this rewrite should actually be used depends on the database engine, indexes, data distribution, and execution plan.

This is a key difference between PawSQL and static rewrite templates: **a rewrite is a candidate; validation determines whether it is valuable.**

## Semantic Safety

SQL rewriting must preserve semantics before it can improve performance.

PawSQL therefore needs to account for:

* NULL semantics
* Aggregation semantics
* DISTINCT behavior
* Outer join semantics
* Data types and implicit conversions
* Dialect differences
* Function and expression behavior

If semantic equivalence cannot be established reliably, a rewrite should not be forced merely for potential performance gain.

## Rewrite Categories

| Category        | Typical examples                                  |
| --------------- | ------------------------------------------------- |
| Predicate       | OR → IN, predicate pushdown                       |
| Subquery        | EXISTS / IN / scalar subquery                     |
| Join            | Join elimination, subquery decorrelation          |
| Aggregation     | DISTINCT / GROUP BY simplification                |
| Pagination      | Deep pagination rewrite                           |
| Distributed SQL | Cross-shard and data movement optimization        |
| Big Data        | Partition, bucket, skew, global sort optimization |

## Related Capabilities

<CardGroup cols={2}>
  <Card title="SQL Quality Check" icon="list-check" href="/en/features/sql-review" />

  <Card title="Index Recommendation" icon="layers" href="/en/features/index-recommendation" />

  <Card title="Performance Validation" icon="gauge" href="/en/features/performance-validation" />

  <Card title="Execution Plan Analysis" icon="route" href="/en/features/execution-plan-visualization" />
</CardGroup>

## Related Use Cases

<CardGroup cols={2}>
  <Card title="Developer SQL Copilot" icon="code" href="/en/use-cases/developer-sql-copilot" />

  <Card title="DBA Batch Slow SQL Governance" icon="gauge" href="/en/use-cases/slow-sql-optimization" />

  <Card title="Database Migration SQL Governance" icon="arrow-right-left" href="/en/use-cases/database-migration-sql-governance" />

  <Card title="Enterprise SQL Governance Platform" icon="building-2" href="/en/use-cases/enterprise-sql-governance" />
</CardGroup>
