Thread: Общие вопросы (General Questions)/Oracle Auto-increment column ("oracle identity" or "oracle auto_increment")

Oracle Auto-increment column ("oracle identity" or "oracle auto_increment")

Oracle does not support the actual SQL standard of IDENTITY... 

you don't actually need to quote your identifiers. Better not to so you don't end up inadvertently using an invalid character in an identifier.

Oracle numerics are called NUMBER, and can take an optional precision and scale.

CREATE TABLE Category
(
  id    NUMBER(11)   NOT NULL,
  title VARCHAR2(45) NULL,
  PRIMARY KEY (id)
)

To do an AUTO_INCREMENT, create a sequence:

CREATE SEQUENCE seq_category_id START WITH 1 INCREMENT BY 1;

Then when you insert into the table, do this:

INSERT INTO category
VALUES (seq_category_id.nextval, 'some title');

To do this automatically, like AUTO_INCREMENT, use a before insert trigger:

-- Automatically create the incremented ID for every row:
CREATE OR REPLACE trigger bi_category_id
BEFORE INSERT ON category
FOR EACH ROW
BEGIN
    SELECT seq_category_id.nextval INTO :new.id FROM dual;
END;

Or:

-- Allow the user to pass in an ID to be used instead
CREATE OR REPLACE TRIGGER bi_category_id
BEFORE INSERT ON category
FOR EACH ROW
DECLARE
    v_max_cur_id NUMBER;
    v_current_seq NUMBER;
BEGIN
    IF :new.id IS NULL THEN
        SELECT seq_category_id.nextval INTO :new.id FROM dual;
    ELSE
        SELECT greatest(nvl(max(id),0), :new.id) INTO v_max_cur_id FROM category;
        SELECT seq_category_id.nextval INTO v_current_seq FROM dual;
        WHILE v_current_seq < v_max_cur_id
        LOOP
            SELECT seq_category_id.nextval INTO v_current_seq FROM dual;
        END LOOP;
    END IF;
END;

Now, as far as discovering these differences, you can often just search for something like "oracle identity" or "oracle auto_increment" to see how Oracle does this.

source