# MariaDB

## Sequence

```
CREATE SEQUENCE 序列名稱
```

\*這是在 MariaDB 10.3 之後才引入的功能

序列是一個生成數值序列的對象。

如果希望控制更多序列號的生成，`Sequence` 是 `AUTO_INCREMENT` 的替代方案。

```
CREATE SEQUENCE 序列名稱 START WITH 起始數字 INCREMENT BY 每次增加多少 ;
```

### 取得 Sequence

```
SELECT NEXT VALUE FOR SEQ_NAME;
OR
SELECT NEXTVAL(SEQ_NAME);

#For Oracle
seqName.nextval;
```

**注意，這個方式只可以用在 CREATE TABLE 的時候。之後要 ALTER TABLE 的時候會被 DENY。**&#x20;

不過習慣上似乎不會這樣寫，通常是在程式 SELECT NEXTVAL(SEQ\_NAME)，再塞入 SEQ，沒塞就讓資料庫噴錯，用來提示程式人員忘記塞。(不建議讓資料庫幫我們塞)

\*在 MariaDB 中，Sequence 作為一種特殊的 表實現，他使用與表相同的命名空間。

好處是序列顯示在 `SHOW TABLES` 中，可以用 `CREATE TABLE` & `DROP TABLE` 去創建序列。

但由於序列在上下文中充當常規表，所以它們將受到 LOCK TABLE 的影響。而這在其他 DBMS 中不是這種情況。

將 `Sequence` 作為表格 `Primary Key`&#x20;

```
create sequence seqName;
create table tableName (
    field1 int primary key default (next value for seqName),
    field2 int
);
```

### 修改 Sequence 的值

```
ALTER SEQUENCE seqName RESTART 50;
```

還有一個方法 SETVAL。

但這個方法只可以改大，如果嘗試改成較小的值，會失敗，return null

```
serval(seqName, 50);
```

### 將 Sequence 移除

```
DROP SEQUENCE seqName;

#因為 MariaDB 將 Sequence 也視為 Table，所以下列這行也可以
DROP TABLE seqName;
```


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://brianwu.gitbook.io/brian/zi-liao-ku/mariadb.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
