# CREATE INDEX

> 在一個或多個資料行或運算式上建立索引，以加速查詢
> Canonical HTML: https://tursodb.cn/zh-tw/docs/sql-reference/statements/create-index/
> Upstream Source (MIT): https://docs.turso.tech/sql-reference/statements/create-index
> Language: zh-TW

---
# CREATE INDEX

在資料表上建立索引，以改善查閱、聯結與排序的查詢效能。

## 語法

```sql
CREATE [UNIQUE] INDEX [IF NOT EXISTS] [schema-name.]index-name
    ON table-name (column-or-expr [COLLATE collation-name] [ASC|DESC], ...)
    [WHERE filter-expression];
```

## 說明

`CREATE INDEX` 會在資料表的一個或多個資料行或運算式上建立索引。Turso 使用與 SQLite 相同格式的 B-tree 索引。查詢規劃器會在索引能加速查詢時自動使用索引——您不需要在 SQL 陳述式中明確引用索引。

### 參數

| 參數 | 說明 |
| - | - |
| `UNIQUE` | 強制執行唯一性條件約束。Turso 會拒絕任何會在已建立索引的資料行中產生重複值的 INSERT 或 UPDATE。 |
| `IF NOT EXISTS` | 若同名的索引已存在，則避免產生錯誤。當索引已存在時，此陳述式不會執行任何操作。 |
| `schema-name` | 包含該資料表的已附加資料庫名稱。若省略則預設為主要資料庫。 |
| `index-name` | 索引在資料庫內的唯一名稱。 |
| `table-name` | 要建立索引的資料表。 |
| `column-or-expr` | 要納入索引的資料行名稱或運算式。多個項目以逗號分隔。 |
| `COLLATE collation-name` | 套用於已建立索引之資料行的選用排序規則順序（例如 `NOCASE`）。 |
| `ASC` / `DESC` | 已建立索引之資料行的排序方向。預設為 `ASC`。 |
| `WHERE filter-expression` | 選用的篩選條件，用於建立部分索引。只有符合該運算式的資料列會納入索引。 |

## 資料行索引

最常見的形式是依名稱對一個或多個資料行建立索引。

```sql
-- Single-column index
CREATE INDEX idx_users_email ON users (email);

-- Multi-column (composite) index
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date DESC);
```

當查詢依多個資料行進行篩選或排序時，複合索引就很有用。資料行的順序很重要——在 `(a, b)` 上的索引可以加速僅依 `a` 篩選的查詢，但無法加速僅依 `b` 篩選的查詢。

## UNIQUE 索引

`UNIQUE` 索引會強制要求任兩個資料列在已建立索引的資料行中不得含有相同的值組合。NULL 值彼此視為不同，因此 `UNIQUE` 索引允許已建立索引的資料行中含有多個 NULL 的資料列。

```sql
CREATE UNIQUE INDEX idx_users_email_unique ON users (email);

-- This succeeds:
INSERT INTO users (email) VALUES ('alice@example.com');

-- This fails with a UNIQUE constraint violation:
INSERT INTO users (email) VALUES ('alice@example.com');
```

## 部分索引

部分索引只包含符合 `WHERE` 子句的資料列。部分索引比完整索引小，對於總是包含相同篩選條件的查詢更有效率。

```sql
-- Index only active orders
CREATE INDEX idx_active_orders ON orders (customer_id)
    WHERE status = 'active';

-- The query planner uses this index when the WHERE clause matches
SELECT * FROM orders WHERE status = 'active' AND customer_id = 42;
```

部分索引的 `WHERE` 子句可以引用資料表的任何資料行，並可使用運算子、常值與內建函式。不允許使用子查詢。

## 運算式索引

運算式索引儲存的是運算式結果，而非原始的資料行值。當查詢經常依計算值進行篩選或排序時，請使用運算式索引。

```sql
-- Index on lowercase email for case-insensitive lookups
CREATE INDEX idx_users_email_lower ON users (lower(email));

-- The query planner can use this index for:
SELECT * FROM users WHERE lower(email) = 'alice@example.com';
```

```sql
-- Index on an arithmetic expression
CREATE INDEX idx_items_total ON items (quantity * unit_price);
```

索引中的每個運算式都必須是確定性的運算式，且只能引用已建立索引之資料表的資料行。不允許使用彙總函式與子查詢。

## 自訂索引方法

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 擴充功能**：自訂索引方法可將索引擴展至 B-tree 之外。此功能為實驗性，使用前必須先[啟用](/zh-tw/docs/sql-reference/experimental-features/)。

</div></div>


Turso 支援 `USING` 子句，用以指定替代的索引方法。

```sql
CREATE INDEX index-name ON table-name USING method-name (columns...);
```

### 使用 `USING fts` 進行全文搜尋

`fts` 索引方法會建立由 Tantivy 驅動的全文搜尋索引。FTS 索引可透過 `WITH` 子句設定分詞器。

```sql
-- Basic FTS index
CREATE INDEX idx_articles_search ON articles USING fts (title, body);

-- FTS index with custom tokenizers
CREATE INDEX idx_articles_search ON articles USING fts (
    title WITH tokenizer=simple,
    body WITH tokenizer=ngram
);
```

一旦 FTS 索引存在，即可使用 `search()` 函式對其查詢：

```sql
SELECT * FROM articles WHERE search(articles, 'database performance');
```

## 範例

### 為常見的查閱模式建立索引

```sql
CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    category TEXT,
    price REAL,
    in_stock INTEGER DEFAULT 1
);

-- Speed up lookups by category
CREATE INDEX idx_products_category ON products (category);

-- Speed up price range queries within a category
CREATE INDEX idx_products_cat_price ON products (category, price);
```

### 使用唯一索引強制執行業務規則

```sql
CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    email TEXT NOT NULL,
    department TEXT
);

CREATE UNIQUE INDEX idx_employees_email ON employees (email);
```

### 針對狀態篩選使用部分索引

```sql
CREATE TABLE tasks (
    id INTEGER PRIMARY KEY,
    assignee TEXT,
    status TEXT DEFAULT 'pending',
    due_date TEXT
);

-- Only index pending tasks -- completed tasks are rarely queried
CREATE INDEX idx_pending_tasks ON tasks (assignee, due_date)
    WHERE status = 'pending';
```

## 另請參閱

* [DROP INDEX](/zh-tw/docs/sql-reference/statements/drop-index/) 以移除索引
* [REINDEX](/zh-tw/docs/sql-reference/statements/reindex/) 以重建索引
* [CREATE TABLE](/zh-tw/docs/sql-reference/statements/create-table/) 以了解內嵌的 UNIQUE 與 PRIMARY KEY 條件約束
* [EXPLAIN](/zh-tw/docs/sql-reference/statements/explain/) 以驗證查詢計畫中的索引使用情形
