> ## 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.

# Optimize Your First SQL Query

> Create a workspace, submit a query, and review rewrite, index, and performance recommendations in PawSQL.

PawSQL analyzes a query in context, identifies potential issues, and produces actionable rewrite, index, and validation results in one workflow. This guide walks you through your first optimization.

<Note>
  This guide follows the core workflow shown in **PawSQL in a Minute**. Initial workspace setup may take a few extra minutes; after that, optimizing a query is a three-step process.
</Note>

## PawSQL in a Minute

<iframe className="w-full aspect-video rounded-xl" src="https://www.youtube.com/embed/5sSjskIeIjo" title="PawsQL Optimize in a Minute - Optimize your queries by Clicks!" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen />

## What you will accomplish

By the end of this guide, you will know how to:

* create or select a workspace;
* submit a query for analysis;
* review SQL findings, automatic rewrites, and index recommendations; and
* compare performance evidence when a database connection is available.

## Before you begin

You need:

* access to a PawSQL deployment and a valid account;
* a `SELECT` statement to analyze; and
* the schema definitions referenced by the query, or access to a database connection.

<Tip>
  For a quick evaluation, create a workspace from DDL—no live database is required. Connect to a database when you need statistics-aware index advice, execution plans, or performance validation.
</Tip>

## Step 1: Create or select a workspace

A workspace stores the database type, version, schema definitions, and available statistics that form the context for optimization. Accurate context helps PawSQL parse the query correctly and produce relevant recommendations.

<Steps>
  <Step title="Open a workspace">
    Sign in to PawSQL. Select an existing workspace, or click **New workspace**.
  </Step>

  <Step title="Choose the database type and version">
    Select the database and version on which the query actually runs. SQL syntax, rewrite rules, and index capabilities vary by database, so avoid selecting an approximate substitute.
  </Step>

  <Step title="Provide schema context">
    Choose the method that fits your environment:

    <Tabs>
      <Tab title="Import DDL">
        Paste or upload the relevant `CREATE TABLE`, `CREATE INDEX`, and related DDL. This is ideal for evaluations, development environments, or cases where direct database access is unavailable.
      </Tab>

      <Tab title="Connect a database">
        Enter the host, port, database name, and a read-only account, then test the connection. PawSQL can read authorized object definitions, statistics, and metadata required for execution-plan analysis.
      </Tab>
    </Tabs>
  </Step>
</Steps>

<Frame caption="Select a workspace, or create one from DDL or a database connection">
  <img src="https://mintcdn.com/pawsql/cdtFYB4QMM1nGHhK/images/quickstart/01-workspace.png?fit=max&auto=format&n=cdtFYB4QMM1nGHhK&q=85&s=e7a19a52064aa2714efce75ad87736ce" alt="Create a workspace: choose a database type and import DDL or connect a database" width="2156" height="1552" data-path="images/quickstart/01-workspace.png" />
</Frame>

<Warning>
  Use a least-privilege, read-only account for production databases. Never expose passwords, internal addresses, or access tokens in screenshots, documentation, or source control.
</Warning>

## Step 2: Submit a query

Open **SQL Optimization** in the workspace and paste the query into the editor.

The following example retrieves the most recent paid orders for a customer:

```sql theme={null}
SELECT o.order_id,
       o.customer_id,
       o.created_at,
       o.total_amount
FROM orders o
WHERE o.customer_id = 10001
  AND o.status = 'PAID'
ORDER BY o.created_at DESC
LIMIT 20;
```

<Steps>
  <Step title="Enter the SQL">
    Paste a complete statement. Keep the real table names, columns, join predicates, and filters because they directly affect findings and index recommendations.
  </Step>

  <Step title="Confirm the context">
    Verify the selected workspace and default database or schema. If the query uses a different schema, qualify the objects in SQL or select the correct schema in the task settings.
  </Step>

  <Step title="Run the optimization">
    Click **Optimize**. PawSQL parses the statement and runs SQL checks, rewrite analysis, and index analysis using the context available in the workspace.
  </Step>
</Steps>

<Frame caption="Confirm the workspace and schema, then submit the query">
  <img src="https://mintcdn.com/pawsql/cdtFYB4QMM1nGHhK/images/quickstart/02-submit-sql.png?fit=max&auto=format&n=cdtFYB4QMM1nGHhK&q=85&s=d0aca2a17fda1b55b6fa569a2b1fed1d" alt="Paste the sample query into the SQL editor before optimizing" width="2156" height="1552" data-path="images/quickstart/02-submit-sql.png" />
</Frame>

## Step 3: Review the results

Start with the summary, then inspect each recommendation. The available result sections depend on the query and workspace context.

<CardGroup cols={2}>
  <Card title="SQL quality check" icon="list-check">
    Surfaces correctness, performance, security, and maintainability risks, with the matched rule and remediation guidance.
  </Card>

  <Card title="Automatic rewrite" icon="wand-sparkles">
    Produces a semantically equivalent candidate that is easier for the database optimizer to execute efficiently.
  </Card>

  <Card title="Index Recommendation" icon="layers">
    Evaluates filter, join, sort, and grouping columns and provides candidate index DDL.
  </Card>

  <Card title="Performance Validation" icon="gauge">
    When a database is connected, compares execution plans or measured behavior before and after optimization.
  </Card>
</CardGroup>

<Frame caption="Open the detailed findings, rewrite, index, and validation views from the result summary">
  <img src="https://mintcdn.com/pawsql/cdtFYB4QMM1nGHhK/images/quickstart/03-optimization-result.png?fit=max&auto=format&n=cdtFYB4QMM1nGHhK&q=85&s=0755cb305a3e35171d7b21ede6bdcedf" alt="Optimization result: index recommendation, review findings, and performance summary" width="2156" height="1552" data-path="images/quickstart/03-optimization-result.png" />
</Frame>

### Recommended review order

1. **Resolve high-priority findings first.** Correctness and security issues usually take precedence over performance-only advice.
2. **Compare the original and rewritten SQL.** Confirm the business meaning, selected columns, and ordering behavior.
3. **Evaluate each proposed index.** Check for existing duplicate or prefix-overlapping indexes and account for write and storage overhead.
4. **Inspect the validation evidence.** Prefer changes supported by an improved execution plan or controlled measurements.

<Warning>
  Do not apply rewritten SQL or create indexes directly in production without validation. Confirm result equivalence in a test environment and follow your organization's change process.
</Warning>

## If no recommendation appears

<AccordionGroup>
  <Accordion title="The SQL cannot be parsed">
    Confirm that the workspace database type and version are correct, the statement is complete, and the query does not rely on unsupported dialect syntax.
  </Accordion>

  <Accordion title="Object information is missing">
    Add the DDL for every referenced table, or verify that the database account can read metadata from the required schema.
  </Accordion>

  <Accordion title="No index is recommended">
    This does not necessarily mean the analysis failed. Existing indexes may already cover the access path, or an additional index may not benefit this query. Review the findings and execution plan together.
  </Accordion>

  <Accordion title="Performance validation is unavailable">
    Validation generally requires a working database connection, sufficient permissions, and representative data. A DDL-only workspace can still support parsing, rule checks, rewrites, and parts of index analysis.
  </Accordion>
</AccordionGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Choose how to use PawSQL" icon="route" href="/en/getting-started/choose-access">
    Compare web, IDE, API, and pipeline workflows.
  </Card>

  <Card title="Supported databases" icon="database" href="/en/getting-started/supported-databases">
    Check database, version, and feature compatibility.
  </Card>

  <Card title="Query Rewrite" icon="git-compare" href="/en/features/automatic-sql-rewrite">
    Learn how rewrites work and where their boundaries are.
  </Card>

  <Card title="Performance Validation" icon="chart-line" href="/en/features/performance-validation">
    Learn how to compare optimization candidates with execution evidence.
  </Card>
</CardGroup>
