> 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/transactions/subxacts.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# 67.3. 子交易 \#

### 67.3. 子交易 [#](#subxacts) <a href="#subxacts" id="subxacts"></a>

子交易是在交易內部開始的，讓大型交易可以拆分成較小的單位。子交易可以提交或中止，而不影響其父交易，讓父交易得以繼續進行。這使錯誤更容易處理，而這是一種常見的應用程式開發模式。subtransaction（子交易）一詞經常縮寫為 *subxact*。

子交易可以使用 `SAVEPOINT` 命令明確開始，也可以透過其他方式開始，例如 PL/pgSQL 的 `EXCEPTION` 子句。 PL/Python 與 PL/Tcl 也支援明確的子交易。子交易也可以從其他子交易中開始。最上層交易及其子交易構成一個階層或樹狀結構，這就是我們把主交易稱為最上層交易的原因。

如果子交易被分配了非虛擬交易 ID， 它的交易 ID 就稱為「subxid」。 唯讀子交易不會被分配 subxid，但一旦它們嘗試寫入，就會被分配一個。這也會使該 subxid 的所有上層交易（直到並包括最上層交易）都被分配非虛擬交易 ID。我們確保父 xid 一定小於它任何子 subxid。

每個 subxid 的直接父 xid 都記錄在 `pg_subtrans` 目錄中。最上層 xid 因為沒有父交易，所以不會為它們建立項目；唯讀子交易也不會建立項目。

當子交易提交時，它所有具有 subxid 且已提交的子交易，在該交易中也會被視為已子提交（subcommitted）。當子交易中止時，它所有的子交易也都會被視為已中止。

當具有 xid 的最上層交易提交時，它所有已子提交的子交易也會在 `pg_xact` 子目錄中被永久記錄為已提交。如果最上層交易中止，它所有的子交易也都會中止，即使它們已經子提交。

每個交易保持開啟（未回復也未釋放）的子交易越多，交易管理的額外負擔就越大。每個後端最多會在共享記憶體中快取 64 個開啟中的 subxid；超過之後，由於需要在 `pg_subtrans` 中額外查找 subxid 項目，儲存 I/O 的額外負擔會顯著增加。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/subxacts.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/transactions/subxacts.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.
