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

# CREATE SEQUENCE

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

The `CREATE SEQUENCE` <InternalLink path="sql-statements">statement</InternalLink> creates a new sequence in a database. Use a sequence to auto-increment integers in a table.

<Note>
  The \`\` statement performs a schema change. For more information about how online schema changes work in CockroachDB, see <InternalLink path="online-schema-changes">Online Schema Changes</InternalLink>.
</Note>

## Considerations

* Using a sequence is slower than <InternalLink path="sql-faqs#how-do-i-auto-generate-unique-row-ids-in-cockroachdb">auto-generating unique IDs with the `gen_random_uuid()`, `uuid_v4()` or `unique_rowid()` built-in functions</InternalLink>. Incrementing a sequence requires a write to persistent storage, whereas auto-generating a unique ID does not. Therefore, use auto-generated unique IDs unless an incremental sequence is preferred or required. For more information, see <InternalLink path="performance-best-practices-overview#unique-id-best-practices">Unique ID best practices</InternalLink>.
* A column that uses a sequence can have a gap in the sequence values if a transaction advances the sequence and is then rolled back. Sequence updates are committed immediately and aren't rolled back along with their containing transaction. This is done to avoid blocking concurrent transactions that use the same sequence.
* We <InternalLink path="schema-design-indexes#best-practices">discourage indexing on sequential keys</InternalLink>. If a table **must** be indexed on sequential keys, use <InternalLink path="hash-sharded-indexes">hash-sharded indexes</InternalLink>. Hash-sharded indexes distribute sequential traffic uniformly across ranges, eliminating single-range <InternalLink path="performance-best-practices-overview#hot-spots">hot spots</InternalLink> and improving write performance on sequentially-keyed indexes at a small cost to read performance.
* By default, you cannot create sequences that are <InternalLink path="security-reference/authorization#object-ownership">owned by</InternalLink> columns in tables in other databases. You can enable such sequence creation by setting the `sql.cross_db_sequence_owners.enabled` <InternalLink path="cluster-settings">cluster setting</InternalLink> to `true`.

## Required privileges

The user must have the `CREATE` <InternalLink path="security-reference/authorization#managing-privileges">privilege</InternalLink> on the parent database.

## Synopsis

<img src="https://mintcdn.com/cockroachlabs/ulDoMGhKYg9RNabd/images/sql-diagrams/v23.1/create_sequence.svg?fit=max&auto=format&n=ulDoMGhKYg9RNabd&q=85&s=0d48a92ad4444bd6ef4b84ae5193c2bb" alt="create_sequence syntax diagram" style={{maxWidth: "100%", overflowX: "auto"}} width="735" height="823" data-path="images/sql-diagrams/v23.1/create_sequence.svg" />

## Parameters

| Parameter                                  | Description                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `seq_name`                                 | The name of the sequence to be created, which must be unique within its database and follow the <InternalLink path="keywords-and-identifiers#identifiers">identifier rules</InternalLink>. When the parent database is not set as the default, the name must be formatted as `database.seq_name`.                                                                                    |
| `INCREMENT`                                | The value by which the sequence is incremented. A negative number creates a descending sequence. A positive number creates an ascending sequence.<br /><br />**Default:** `1`                                                                                                                                                                                                        |
| `MINVALUE`                                 | The minimum value of the sequence. Default values apply if not specified or if you enter `NO MINVALUE`.<br /><br />**Default for ascending:** `1` <br /><br />**Default for descending:** `MININT`                                                                                                                                                                                   |
| `MAXVALUE`                                 | The maximum value of the sequence. Default values apply if not specified or if you enter `NO MAXVALUE`.<br /><br />**Default for ascending:** `MAXINT` <br /><br />**Default for descending:** `-1`                                                                                                                                                                                  |
| `START [WITH]`                             | The first value of the sequence. <br /><br />**Default for ascending:** `1` <br /><br />**Default for descending:** `-1`                                                                                                                                                                                                                                                             |
| `RESTART [WITH]`                           | Sets `nextval` to the specified number, or back to the original `START` value.                                                                                                                                                                                                                                                                                                       |
| `NO CYCLE`                                 | All sequences are set to `NO CYCLE` and the sequence will not wrap.                                                                                                                                                                                                                                                                                                                  |
| `CACHE`                                    | The number of sequence values to cache in memory for reuse in the session. A cache size of `1` means that there is no cache, and cache sizes of less than `1` are not valid.<br /><br />**Default:** `1` (sequences are not cached by default)                                                                                                                                       |
| <a id="owned-by" /> `OWNED BY column_name` | Associates the sequence to a particular column. If that column or its parent table is dropped, the sequence will also be dropped.<br />Specifying an owner column with `OWNED BY` replaces any existing owner column on the sequence. To remove existing column ownership on the sequence and make the column free-standing, specify `OWNED BY NONE`.<br /><br />**Default:** `NONE` |
| `opt_temp`                                 | Defines the sequence as a session-scoped temporary sequence. For more information, see [Temporary sequences](#temporary-sequences).                                                                                                                                                                                                                                                  |

## Sequence functions

CockroachDB supports the following <InternalLink path="functions-and-operators">SQL sequence functions</InternalLink>:

* `nextval('seq_name')`
* `currval('seq_name')`
* `lastval()`
* `setval('seq_name', value, is_called)`

## Temporary sequences

CockroachDB supports session-scoped temporary sequences. Unlike persistent sequences, temporary sequences can only be accessed from the session in which they were created, and they are dropped at the end of the session. You can create temporary sequences on both persistent tables and <InternalLink path="temporary-tables">temporary tables</InternalLink>.

<Note>
  **This feature is in <InternalLink path="cockroachdb-feature-availability">preview</InternalLink>** and subject to change. To share feedback and/or issues, contact [Support](https://support.cockroachlabs.com).
</Note>

<Note>
  Temporary tables must be enabled in order to use temporary sequences. By default, temporary tables are disabled in CockroachDB. To enable temporary tables, set the `experimental_enable_temp_tables` <InternalLink path="set-vars">session variable</InternalLink> to `on`.
</Note>

### Details

* Temporary sequences are automatically dropped at the end of the session.
* A temporary sequence can only be accessed from the session in which it was created.
* Temporary sequences persist across transactions in the same session.
* Temporary sequences cannot be converted to persistent sequences.

<Note>
  Like <InternalLink path="temporary-tables">temporary tables</InternalLink>, temporary sequences are not in the `public` schema. Instead, when you create the first temporary table, view, or sequence for a session, CockroachDB generates a single temporary schema (`pg_temp_<id`) for all of the temporary objects in the current session for a database.
</Note>

### Usage

To create a temporary sequence, add <InternalLink path="sql-grammar">`TEMP`/`TEMPORARY`</InternalLink> to a `CREATE SEQUENCE` statement.

For example:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SET experimental_enable_temp_tables=on;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TEMP SEQUENCE temp_seq START 1 INCREMENT 1;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW CREATE temp_seq;
```

```
  table_name |                                     create_statement
-------------+--------------------------------------------------------------------------------------------
  temp_seq   | CREATE TEMP SEQUENCE temp_seq MINVALUE 1 MAXVALUE 9223372036854775807 INCREMENT 1 START 1
(1 row)
```

## Examples

### Create a sequence with default settings

In this example, we create a sequence with default settings.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE SEQUENCE customer_seq;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW CREATE customer_seq;
```

```
   table_name  |                                     create_statement
---------------+-------------------------------------------------------------------------------------------
  customer_seq | CREATE SEQUENCE customer_seq MINVALUE 1 MAXVALUE 9223372036854775807 INCREMENT 1 START 1
(1 row)
```

### Use a sequence when creating a table

In this example, we <InternalLink path="create-table">create a table</InternalLink>, using the <InternalLink path="functions-and-operators">`nextval()` function</InternalLink> for a <InternalLink path="default-value">default value</InternalLink>, with the `customer_seq` sequence as its input:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE customers (
    uid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    rownum INT DEFAULT nextval('customer_seq'),
    name STRING
);
```

Inserting into this table with an `INSERT` statement that relies on default values will call `nextval`, which increments the sequence.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO customers (name) VALUES ('Max'), ('Alice');
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT * FROM customers;
```

```
                  uid                  | rownum | name
---------------------------------------+--------+--------
  1c7f5b79-88c4-49ec-b40b-6098d28bb822 |      2 | Alice
  7ce844af-6a3f-4c52-ba07-25623f345804 |      1 | Max
(2 rows)
```

### View the current value of a sequence

To view the current value without incrementing the sequence, use:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT * FROM customer_seq;
```

```
  last_value | log_cnt | is_called
-------------+---------+------------
           2 |       0 |   true
(1 row)
```

If a value has been obtained from the sequence in the current session, you can also use the `currval('seq_name')` function to get that most recently obtained value:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT currval('customer_seq');
```

```
  currval
-----------
        2
(1 row)
```

### Set the next value of a sequence

In this example, we're going to change the next value of `customer_seq` using the <InternalLink path="functions-and-operators">`setval()` function</InternalLink>. Currently, the next value will be `3` (i.e., `2` + `INCREMENT 1`). We will change the next value to `5`.

<Note>
  You cannot set a value outside the `MAXVALUE` or `MINVALUE` of the sequence.
</Note>

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT setval('customer_seq', 5, false);
```

```
  setval
----------
       5
(1 row)
```

<Note>
  The `setval('seq_name', value, is_called)` function in CockroachDB SQL mimics the `setval()` function in PostgreSQL, but it does not store the `is_called` flag. Instead, it sets the value to `val - increment` for `false` or `val` for `true`.
</Note>

Let's add another record to the table to check that the new record adheres to the new next value.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO customers (name) VALUES ('Sam');
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT * FROM customers;
```

```
                  uid                  | rownum | name
---------------------------------------+--------+--------
  19ffe03d-5eac-4a2f-8aa8-1569b998aa44 |      5 | Sam
  1c7f5b79-88c4-49ec-b40b-6098d28bb822 |      2 | Alice
  7ce844af-6a3f-4c52-ba07-25623f345804 |      1 | Max
(3 rows)
```

### Create a sequence with user-defined settings

In this example, we create a sequence that starts at -1 and descends in increments of 2.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE SEQUENCE desc_customer_list START -1 INCREMENT -2;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW CREATE desc_customer_list;
```

```
      table_name     |                                          create_statement
---------------------+-----------------------------------------------------------------------------------------------------
  desc_customer_list | CREATE SEQUENCE desc_customer_list MINVALUE -9223372036854775808 MAXVALUE -1 INCREMENT -2 START -1
(1 row)
```

### List all sequences

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW SEQUENCES;
```

```
         sequence_schema        |   sequence_name
--------------------------------+---------------------
  public                        | customer_seq
  public                        | desc_customer_list
  pg_temp_1603124728816183000_1 | temp_seq
(3 rows)
```

### Cache sequence values in memory

For improved performance, use the `CACHE` keyword to cache sequence values in memory.

For example, to cache 10 sequence values in memory:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE SEQUENCE customer_seq_cached CACHE 10;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW CREATE customer_seq_cached;
```

```
      table_name      |                                                create_statement
----------------------+------------------------------------------------------------------------------------------------------------------
  customer_seq_cached | CREATE SEQUENCE public.customer_seq_cached MINVALUE 1 MAXVALUE 9223372036854775807 INCREMENT 1 START 1 CACHE 10
(1 row)
```

## See also

* <InternalLink path="alter-sequence">`ALTER SEQUENCE`</InternalLink>
* <InternalLink path="drop-sequence">`DROP SEQUENCE`</InternalLink>
* <InternalLink path="show-create">`SHOW CREATE`</InternalLink>
* <InternalLink path="show-sequences">`SHOW SEQUENCES`</InternalLink>
* <InternalLink path="functions-and-operators">Functions and Operators</InternalLink>
* <InternalLink path="sql-statements">SQL Statements</InternalLink>
* <InternalLink path="online-schema-changes">Online Schema Changes</InternalLink>
