DEV Community

Edgar Rios Navarro
Edgar Rios Navarro

Posted on

Autoincrement en Oracle

Consideremos el script original, basado en la versión 11g:

---------
-- 11g --
---------
CREATE TABLE ORDERS (
    ID NUMBER NOT NULL,
    ...
);
/

ALTER TABLE ORDERS 
ADD CONSTRAINT PK_ID PRIMARY KEY (ID);
/

CREATE SEQUENCE SEQ_ORDERS
 START WITH     1000
 INCREMENT BY   1
 NOCACHE
 NOCYCLE;
/

CREATE OR REPLACE TRIGGER TRG_I_ORDERS
BEFORE INSERT
   ON ORDERS
   FOR EACH ROW
BEGIN
   :NEW.ID = SEQ_ORDERS.NEXTVAL
END;
/
Enter fullscreen mode Exit fullscreen mode

Anteriormente, se empleaba un trigger para incrementar el ID: recuperar el valor de un sequence y asignarlo al campo.


Desde la versión 12c, obtenemos la misma funcionalidad con IDENTITY Column.

---------
-- 12c --
---------

CREATE TABLE ORDERS(
    ID NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    ...
);
/
Enter fullscreen mode Exit fullscreen mode

Documentación

Oracle:Database:identity_clause

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay