# G-3150: Try to use identity columns for surrogate keys.

Minor

Maintainability, Reliability

ORACLE 12c

## Reason

An identity column is a surrogate key by design – there is no reason why we should not take advantage of this natural implementation when the keys are generated on database level. Using identity column (and therefore assigning sequences as default values on columns) has a huge performance advantage over a trigger solution.

CREATE TABLE locations (
location_id        NUMBER(10)        NOT NULL
,location_name      VARCHAR2(60 CHAR) NOT NULL
,city               VARCHAR2(30 CHAR) NOT NULL
,CONSTRAINT locations_pk PRIMARY KEY (location_id)
)
/

/

CREATE OR REPLACE TRIGGER location_br_i
BEFORE INSERT ON LOCATIONS
FOR EACH ROW
BEGIN
:new.location_id := location_seq.nextval;
END;
/


## Example (good)

CREATE TABLE locations (
location_id        NUMBER(10)  GENERATED ALWAYS AS IDENTITY
,location_name      VARCHAR2(60 CHAR) NOT NULL
,city               VARCHAR2(30 CHAR) NOT NULL
,CONSTRAINT locations_pk PRIMARY KEY (location_id))
/


GENERATED ALWAYS AS IDENTITY ensures that the location_id is populated by a sequence. It is not possible to override the behavior in the application.

However, if you use a framework that produces an INSERT statement including the surrogate key column, and you cannot change this behavior, then you have to use the GENERATED BY DEFAULT ON NULL AS IDENTITY option. This has the downside that the application may pass a value, which might lead to an immediate or delayed ORA-00001: unique constraint violated error.