📜  oracle auto_increment - SQL (1)

📅  最后修改于: 2023-12-03 15:18:08.328000             🧑  作者: Mango

Oracle Auto_Increment - SQL

Auto-increment is a feature that automatically generates a unique number sequence or series in an Oracle database. It is a useful feature for creating unique keys in tables without having to manually assign and track them. In Oracle, auto-increment is achieved using the SEQUENCE keyword.

Creating a Sequence

In Oracle, a sequence is created using the CREATE SEQUENCE statement. Here is an example of how to create a simple sequence:

CREATE SEQUENCE Example_Seq START WITH 1 INCREMENT BY 1;

This creates a sequence named Example_Seq that starts at 1 and increments by 1. The sequence can then be used to set a default value for a column in a table.

Using a Sequence in a Table

To use a sequence in a table, you need to define a column as a sequence-generated value. Here's an example table definition that uses a sequence to generate unique IDs:

CREATE TABLE Example_Table (
    id NUMBER DEFAULT Example_Seq.NEXTVAL PRIMARY KEY,
    name VARCHAR2(50),
    age NUMBER
);

In this example, the id column is defined with a default value of Example_Seq.NEXTVAL, which will generate the next value in the sequence when a new row is added to the table. The id column is also defined as the primary key of the table.

Inserting Data into the Table

To insert data into the table, you can omit the id column and it will automatically be generated by the sequence. Here's an example of how to insert data into the table:

INSERT INTO Example_Table (name, age)
VALUES ('John Doe', 30);

This will insert a new row into the Example_Table table with an automatically-generated id of 1 (since it's the first row to be added).

Conclusion

Auto-increment is a useful feature in Oracle for generating unique IDs in a table without having to manually assign them. By using a sequence, you can simplify the process of creating and tracking unique keys in your database.