CREATE SEQUENCE 语句用来创建序列,语法格式如下:

    1. CREATE SEQUENCE sequence_name
    2. [MINVALUE value | NOMINVALUE]
    3. [MAXVALUE value | NOMAXVALUE]
    4. [START WITH value]
    5. [INCREMENT BY value]
    6. [CACHE value | NOCACHE]
    7. [ORDER | NOORDER]
    8. [CYCLE | NOCYCLE];

    其中,MINVALUE 和 MAXVALUE 指定最小值和最大值;START WITH 指定起始值;INCREMENT BY 指定步长,可以为负数,默认是1;CACHE 是为了性能缓存部分序列值,并发高的时候使用;CYCLE 指定序列值是否循环,如果循环,需要指定最大值或最小值。

    示例:创建序列,实现表的列自增。

    1. obclient> create table t1(id number not null primary key, name varchar(50) , gmt_create date not null default sysdate);
    2. Query OK, 0 rows affected (0.07 sec)
    3. obclient> create sequence seq_t1 start with 10000 increment by 1 cache 50 nocycle;
    4. Query OK, 0 rows affected (0.04 sec)
    5. obclient> insert into t1(id,name) values(seq_t1.nextval, 'A');
    6. Query OK, 1 row affected (0.02 sec)
    7. obclient> insert into t1(id,name) values(seq_t1.nextval, 'B');
    8. Query OK, 1 row affected (0.00 sec)
    9. obclient> insert into t1(id,name) values(seq_t1.nextval, 'C');
    10. Query OK, 1 row affected (0.00 sec)
    11. obclient> select * from t1;
    12. +-------+------+---------------------+
    13. | ID | NAME | GMT_CREATE |
    14. +-------+------+---------------------+
    15. | 10000 | A | 2020-04-02 18:30:29 |
    16. | 10001 | B | 2020-04-02 18:30:34 |
    17. | 10002 | C | 2020-04-02 18:30:39 |
    18. +-------+------+---------------------+
    19. 3 rows in set (0.01 sec)

    序列创建成功后,可以通过 USER_SEQUENCES、ALL_SEQUENCES、DBA_SEQUENCES 视图查看自己创建的序列。

    1. obclient> select * from user_sequences \G
    2. *************************** 1. row ***************************
    3. SEQUENCE_NAME: SEQ_T1
    4. MIN_VALUE: 1
    5. MAX_VALUE: 9999999999999999999999999999
    6. INCREMENT_BY: 1
    7. CYCLE_FLAG: N
    8. ORDER_FLAG: N
    9. CACHE_SIZE: 50
    10. LAST_NUMBER: 10100
    11. 1 row in set (0.00 sec)
    12. obclient>