Sub topic 8
Generating keys with identity columns
This chapter assumes you can write basic CREATE TABLE statements, know what a primary key is, and have an Oracle Database 12c or later schema to run the examples in. Identity columns first appeared in Oracle 12c. Every example below runs as shown on 12c and later.
What an identity column is
An identity column is a numeric column whose value Oracle generates for you when you insert a row. You declare it in CREATE TABLE with the GENERATED ... AS IDENTITY clause. You no longer need to create a sequence and a trigger by hand, and your INSERT statements can leave the key out.
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);Three things happen when this statement runs:
- Oracle creates the table and the
department_idcolumn. - Oracle creates a system-managed sequence, with a name like
ISEQ$$_12345, and attaches it to the column. - Oracle makes the column
NOT NULLautomatically.
You do not need to declare NOT NULL on an identity column. An identity column is not automatically a primary key, though. Without the PRIMARY KEY constraint, the column would be generated but not guaranteed unique.
Inserting rows
Leave the identity column out of the column list and Oracle fills it in.
-- The identity value is generated; do not supply one.
INSERT INTO departments (department_name) VALUES ('Sales');You can check the generated value afterward:
SELECT department_id, department_name FROM departments;The first row gets 1, the default starting value. To get the generated key back into your program, use a RETURNING clause (in PL/SQL) or the equivalent in your driver:
DECLARE
v_id departments.department_id%TYPE;
BEGIN
INSERT INTO departments (department_name)
VALUES ('Marketing')
RETURNING department_id INTO v_id;
DBMS_OUTPUT.PUT_LINE('New id: ' || v_id);
END;
/RETURNING is safer than running SELECT MAX(department_id) afterward. The MAX approach can return another session's row.
The data model behind identity columns
An identity column is a sequence plus a column default, bundled together by the database. That has several consequences:
- The sequence is owned by the table. Dropping the table drops the sequence.
- You cannot drop or alter the system sequence directly. You change it through
ALTER TABLE ... MODIFY. - The value is generated at INSERT time, as part of the same statement, but sequence values are never rolled back.
The three generation modes
The keyword after GENERATED controls what happens when an INSERT supplies a value for the identity column.
| Mode | Explicit value | Explicit NULL | Value omitted |
|---|---|---|---|
| `GENERATED ALWAYS` | Rejected with ORA-32795 | Rejected with ORA-32795 | Generated |
| `GENERATED BY DEFAULT` | Accepted | Rejected with ORA-01400 | Generated |
| `GENERATED BY DEFAULT ON NULL` | Accepted | Replaced by a generated value | Generated |
The next script exercises all three behaviors. The employees table uses BY DEFAULT ON NULL.
-- The identity value is generated; do not supply one.
INSERT INTO departments (department_name) VALUES ('Sales');
-- Fails with ORA-32795 because the column is GENERATED ALWAYS.
INSERT INTO departments (department_id, department_name) VALUES (99, 'Support');
-- BY DEFAULT ON NULL accepts an explicit value, and generates one when NULL is supplied.
INSERT INTO employees (employee_id, email) VALUES (5000, '[email protected]');
INSERT INTO employees (employee_id, email) VALUES (NULL, '[email protected]');The second statement fails by design. The Sales insert may also fail on a second run, because departments_name_uk makes the name unique. Rerun the script on a clean schema.
Choosing a mode
- Use
ALWAYSwhen the key is purely internal and nobody should set it. It protects you from application code that invents ids. Its drawback is that data loads and migrations that must preserve existing ids cannot insert them, unless you temporarily change the column. - Use
BY DEFAULTwhen you sometimes need to supply ids, for example when copying data from another system. It still lets a careless statement collide with generated values. - Use
BY DEFAULT ON NULLwhen applications or ORMs send an explicitNULLfor the key. With plainBY DEFAULT, thatNULLraises an error. WithON NULL, Oracle substitutes a generated value.
One way to move the generator is ALTER TABLE ... MODIFY ... GENERATED ... AS IDENTITY (START WITH LIMIT VALUE). This restarts the sequence at the current highest value in the column plus the increment:
ALTER TABLE employees
MODIFY employee_id GENERATED BY DEFAULT ON NULL AS IDENTITY
(START WITH LIMIT VALUE);LIMIT VALUE is available in Oracle 12.2 and later, and it works only for ascending sequences.
Identity options
You can customize the sequence inside the parentheses after AS IDENTITY. The employees table uses three options:
CREATE TABLE employees (
employee_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY
(START WITH 1000 INCREMENT BY 1 CACHE 20),
email VARCHAR2(255) NOT NULL,
salary NUMBER(10,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL,
hire_date DATE DEFAULT SYSDATE NOT NULL,
department_id NUMBER,
CONSTRAINT employees_pk PRIMARY KEY (employee_id),
CONSTRAINT employees_email_uk UNIQUE (email),
CONSTRAINT employees_salary_ck CHECK (salary >= 0),
CONSTRAINT employees_status_ck CHECK (status IN ('ACTIVE', 'INACTIVE')),
CONSTRAINT employees_dept_fk FOREIGN KEY (department_id)
REFERENCES departments (department_id)
ON DELETE SET NULL
);START WITH 1000sets the first generated value.INCREMENT BY 1sets the step. A negative step produces descending values, and you would then also setSTART WITHappropriately.CACHE 20makes Oracle preallocate 20 values in memory, so it does not touch the data dictionary on every insert. The default is 20.
Other sequence options, such as MAXVALUE, MINVALUE, CYCLE and ORDER, are also accepted.
Gaps are normal
Identity values are not gapless. Gaps appear in these situations:
- An INSERT fails or is rolled back. The sequence value it consumed is gone.
- The instance shuts down or the cache is aged out of the shared pool. Unused cached values are lost.
- A
CACHEvalue larger than 1 is in use and sessions run on different RAC nodes. Each node keeps its own cache, so values may not appear in insert order.
Do not use an identity column to produce invoice numbers that legally must be consecutive. For that, you need a separate design, such as a counter table with row locking.
Order is not guaranteed either
Generated values are unique and increasing within a single sequence, but a later commit can carry a smaller number than an earlier one. Do not sort by the identity column and assume the result equals the order of arrival. Use a timestamp column such as hire_date or created_at for that.
Restrictions
Identity columns have limits you should know before you design a table:
- A table can have only one identity column.
- The column must be numeric (
NUMBER,INTEGER,FLOATand similar types). - An identity column cannot have a
DEFAULTclause, because the identity clause is the default. - Identity columns are not allowed on object tables or temporary tables in some configurations. Check the documentation for your release if you need them there.
UPDATEof anALWAYSidentity column is rejected. Oracle treats the generated value as read-only after creation.
Inspecting identity columns
The data dictionary shows which columns are identity columns, their mode, and the sequence that supports them.
SELECT constraint_name, constraint_type, status, validated
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
ORDER BY constraint_name;
SELECT table_name, column_name, generation_type, sequence_name
FROM user_tab_identity_cols;In user_tab_identity_cols, generation_type shows ALWAYS, BY DEFAULT or BY DEFAULT ON NULL. To see the current sequence settings, query user_sequences using the name from the sequence_name column:
SELECT sequence_name, min_value, max_value, increment_by, cache_size, last_number
FROM user_sequences
WHERE sequence_name IN (SELECT sequence_name FROM user_tab_identity_cols);last_number includes values already cached in memory, so it can be ahead of the largest id you have inserted.
Common errors
| Error | Cause | Fix |
|---|---|---|
| ORA-32795 | You supplied a value for a `GENERATED ALWAYS` column | Remove the column from the INSERT, or change the mode |
| ORA-01400 | You supplied `NULL` to a plain `BY DEFAULT` column | Omit the column, or use `BY DEFAULT ON NULL` |
| ORA-00001 on an insert you did not give an id for | A manually supplied id collides with the sequence | Restart the generator past the largest id |
| ORA-30673 or ORA-32793 | You tried to alter or drop the system sequence directly | Use `ALTER TABLE ... MODIFY` |
Summary
An identity column gives you a key generator tied to the table, with three modes that decide who may supply values. Pick ALWAYS for strict control, BY DEFAULT for flexible loads, and BY DEFAULT ON NULL when clients send NULL. Tune START WITH, INCREMENT BY and CACHE as needed, expect gaps, and look at user_tab_identity_cols when you need to see what the database created.
Exercise
A table has id NUMBER GENERATED BY DEFAULT AS IDENTITY. An application inserts a row with id set explicitly to NULL. What happens, and which single change to the column definition makes the insert succeed with a generated value?
Show answer
The insert fails with ORA-01400, because plain BY DEFAULT does not replace NULL with a generated value, and the identity column is NOT NULL. Changing the mode to GENERATED BY DEFAULT ON NULL AS IDENTITY makes Oracle substitute the next sequence value when NULL is supplied.
Exercise
You loaded 500 rows into a GENERATED BY DEFAULT identity table with ids 1 to 500 supplied by hand. The next insert without an id fails with ORA-00001. Why, and how do you fix it?
Show answer
The system sequence started at 1 and knows nothing about the ids you inserted manually, so it generates 1 and collides with the existing primary key. Fix it by moving the generator past the highest existing id, for example ALTER TABLE t MODIFY id GENERATED BY DEFAULT AS IDENTITY (START WITH LIMIT VALUE); (Oracle 12.2 or later).