> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/19/internals/overview/query-path.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# 51.1. 查詢的路徑 \#

### 51.1. 查詢的路徑 [#](#query-path) <a href="#query-path" id="query-path"></a>

這裡簡短概述一個查詢為了取得結果所必須經過的各個階段。

1. 必須先建立從應用程式到 PostgreSQL 伺服器的連線。應用程式將查詢傳送到伺服器，並等待接收伺服器傳回的結果。
2. *剖析器階段*會檢查應用程式所傳送之查詢的語法是否正確，並建立一棵*查詢樹*。
3. *重寫系統*會取得剖析器階段所建立的查詢樹，並尋找任何要套用到該查詢樹的*規則*（儲存在*系統目錄*中），然後執行*規則主體*中所指定的轉換。

   重寫系統的應用之一是實現*檢視表*。每當對檢視表（也就是*虛擬資料表*）發出查詢時，重寫系統會將使用者的查詢改寫成一個改為存取*檢視表定義*中所指定之*基底資料表*的查詢。
4. *規劃器／最佳化器*會取得（經過重寫的）查詢樹，並建立一個*查詢計畫*，作為*執行器*的輸入。

   它的做法是先建立所有能得到相同結果的可能*路徑*。例如，若要掃描的關聯上有索引，該掃描就有兩條路徑：一種可能是單純的循序掃描，另一種可能是使用索引。接著會估算執行每條路徑的成本，並選出成本最低的路徑。成本最低的路徑會被展開成執行器可以使用的完整計畫。
5. 執行器會遞迴地逐步走訪*計畫樹*，並以計畫所表示的方式取得資料列。執行器在掃描關聯時會使用*儲存系統*，執行*排序*與*連接*、評估*限定條件*，最後傳回推導出的資料列。

在接下來的各節中，我們會更詳細地說明上面列出的每一項，讓你更了解 PostgreSQL 的內部控制與資料結構。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/query-path.html)（原文版本：18.6；核對日期：2026-10-12）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.postgresql.tw/19/internals/overview/query-path.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
