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

# 排序與分頁

> 使用 orderBy 輸入物件對查詢結果排序，並以 limit 分頁 — 命名慣例、預設值與基於 offset 的分頁

## orderBy InputObject

每個 Cube 會生成 `{Cube}OrderBy` 輸入物件，包含 `ascending` 與 `descending` 欄位。每個欄位接受 `CompareFields` 列舉值，命名規則為維度路徑以下劃線連線：

```
{DimensionGroup}_{DimensionField}
```

巢狀維度逐級拼接：

```
Block_Time
Trade_Buy_Amount
Trade_Buy_PriceInUSD
```

用法：

```graphql theme={null}
orderBy: {descending: Block_Time}      # newest first
orderBy: {ascending: Trade_Buy_Amount}  # smallest amount first
```

### 常見 CompareFields 取值

<div style={{ overflowX: 'auto', width: '100%' }}>
  | CompareFields 值        | 示例用法                                          | Cube                                                                              | 說明            |
  | :--------------------- | :-------------------------------------------- | :-------------------------------------------------------------------------------- | :------------ |
  | `Block_Time`           | `orderBy: {descending: Block_Time}`           | DEXTrades, Transfers, BalanceUpdates, DEXPools, TokenSupplyUpdates, Pairs, Tokens | 最新的在前         |
  | `Block_Time`           | `orderBy: {ascending: Block_Time}`            | DEXTrades, Transfers, BalanceUpdates, DEXPools, TokenSupplyUpdates, Pairs, Tokens | 最舊的在前         |
  | `Interval_Time_Start`  | `orderBy: {ascending: Interval_Time_Start}`   | Pairs, Tokens                                                                     | 最舊的在前（區間起始時間） |
  | `Trade_Buy_Amount`     | `orderBy: {descending: Trade_Buy_Amount}`     | DEXTrades                                                                         | 買入量大的在前       |
  | `Trade_Buy_PriceInUSD` | `orderBy: {descending: Trade_Buy_PriceInUSD}` | DEXTrades                                                                         | USD 價高的在前     |
  | `Transfer_AmountInUSD` | `orderBy: {descending: Transfer_AmountInUSD}` | Transfers                                                                         | USD 轉賬額大的在前   |
  | `LatestBalanceUSD`     | `orderBy: {descending: LatestBalanceUSD}`     | TokenHolders                                                                      | 持倉 USD 大的在前   |
  | `BuyVolumeUSDState`    | `orderBy: {descending: BuyVolumeUSDState}`    | WalletTokenPnL                                                                    | 買入量 USD 高的在前  |
</div>

<Tip>
  在 [GraphQL IDE](https://ide.chainstream.io) 中用自動補全檢視某 Cube 可用的全部 `CompareFields`——輸入 `orderBy: {descending:` 後 IDE 會列出可選欄位。
</Tip>

### 用法

傳入 `orderBy` 輸入物件，將 `descending` 或 `ascending` 設為某個 `CompareFields` 值：

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      orderBy: {descending: Block_Time}
      limit: { count: 10 }
    ) {
      Block { Time }
      Trade { Buy { Amount PriceInUSD } }
    }
  }
}
```

<Note>
  `orderBy` 僅接受**單一**方向/欄位對。不支援多列排序——查詢每次只按一個維度排序。
</Note>

***

## limit 引數

`limit` 控制返回行數，並支援基於 offset 的分頁：

```graphql theme={null}
input LimitInput {
  count: Int   # Number of rows to return
  offset: Int  # Number of rows to skip
}
```

### 預設與最大限制

每個 Cube 在省略 `limit` 時有**預設**行數，並有**最大**上限：

| Cube               | 預設 `count` | 最大 `count` |
| :----------------- | :--------- | :--------- |
| DEXTrades          | 25         | 10,000     |
| Transfers          | 25         | 10,000     |
| BalanceUpdates     | 25         | 10,000     |
| DEXPools           | 25         | 10,000     |
| TokenSupplyUpdates | 25         | 10,000     |
| Pairs              | 25         | 10,000     |
| Tokens             | 25         | 10,000     |
| DEXPoolEvents      | 25         | 10,000     |
| TokenHolders       | 25         | 10,000     |
| WalletTokenPnL     | 25         | 10,000     |

<Info>
  若請求的 `count` 超過最大值，服務端會靜默截斷為最大允許值。
</Info>

***

## 基於 Offset 的分頁

使用 `offset` 翻頁，模式很直接：

* **第 1 頁**：`limit: { count: 50, offset: 0 }`
* **第 2 頁**：`limit: { count: 50, offset: 50 }`
* **第 3 頁**：`limit: { count: 50, offset: 100 }`

### 示例：代幣持有者分頁

<Tabs>
  <Tab title="第 1 頁">
    ```graphql theme={null}
    query {
      Solana {
        TokenHolders(
          tokenAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
          orderBy: {descending: LatestBalanceUSD}
          limit: { count: 20, offset: 0 }
        ) {
          Holder { Address }
          LatestBalance
          LatestBalanceUSD
        }
      }
    }
    ```
  </Tab>

  <Tab title="第 2 頁">
    ```graphql theme={null}
    query {
      Solana {
        TokenHolders(
          tokenAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
          orderBy: {descending: LatestBalanceUSD}
          limit: { count: 20, offset: 20 }
        ) {
          Holder { Address }
          LatestBalance
          LatestBalanceUSD
        }
      }
    }
    ```
  </Tab>
</Tabs>

### 分頁建議

<AccordionGroup>
  <Accordion title="分頁務必配合 orderBy">
    沒有穩定排序時，行間順序可能在翻頁時變化。請始終將 `limit` 與能產生確定順序的 `orderBy` 一起使用。
  </Accordion>

  <Accordion title="避免過大 offset">
    很大的 `offset`（例如 50,000+）可能拖慢查詢，因為資料庫需掃描並跳過行。對超大結果集，優先用 `where` 收窄查詢，而非深度 offset 翻頁。
  </Accordion>

  <Accordion title="用 count 判斷是否到底">
    若某頁返回行數少於請求的 `count`，說明已到達結果末尾。也可事先用 `count` 指標欄位獲取總行數。
  </Accordion>
</AccordionGroup>

***

## 實用示例

### 最新大額成交

獲取 Solana 上最近 10 筆買入名義價值超過 10,000 美元的 DEX 成交：

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      where: {
        Trade: { Buy: { PriceInUSD: { gt: 10000 } } }
      }
      orderBy: {descending: Block_Time}
      limit: { count: 10 }
    ) {
      Block { Time }
      Trade {
        Buy {
          Currency { MintAddress }
          Amount
          PriceInUSD
        }
        Dex { ProtocolName }
      }
    }
  }
}
```

### OHLC K 線——最近 60 分鐘

獲取某代幣 1 分鐘 K 線，按時間正序：

```graphql theme={null}
query {
  Trading {
    Pairs(
      where: {
        Token: { Address: { is: "So11111111111111111111111111111111111111112" } }
        Market: { Network: { is: "sol" } }
        Block: { Time: { after: "2025-03-27T09:00:00Z" } }
      }
      orderBy: {ascending: Block_Time}
      limit: { count: 60 }
    ) {
      Block { Time }
      Price {
        Ohlc { Open High Low Close }
      }
      Volume { Usd }
      Stats { TradeCount }
    }
  }
}
```

### Top 50 代幣持有者

按 USD 餘額排序取前 50 名持有者：

```graphql theme={null}
query {
  Solana {
    TokenHolders(
      tokenAddress: "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"
      orderBy: {descending: LatestBalanceUSD}
      limit: { count: 50 }
    ) {
      Holder { Address }
      LatestBalance
      LatestBalanceUSD
      FirstSeen
      LastSeen
    }
  }
}
```

***

## 下一步

<CardGroup cols={2}>
  <Card title="篩選" icon="filter" href="/zh-Hant/graphql/schema/filtering">
    將排序與篩選結合，構建精確的分析查詢。
  </Card>

  <Card title="指標與聚合" icon="chart-simple" href="/zh-Hant/graphql/schema/metrics-aggregation">
    使用 count、sum、avg、min、max、uniq 對已排序資料聚合。
  </Card>
</CardGroup>
