Sub topic 9
ALWAYS vs BY DEFAULT vs BY DEFAULT ON NULL
This chapter assumes you can write a CREATE TABLE statement and that you know what an identity column is from the previous chapter. It covers how Oracle's three identity generation modes behave on INSERT and UPDATE, which errors each one raises, and how to choose between them.
The three modes
An identity column is backed by a system-managed sequence. The generation clause decides who controls the value: Oracle alone, or Oracle and the application together.
| Clause | Value omitted | `DEFAULT` keyword | Explicit value | Explicit `NULL` |
|---|---|---|---|---|
| `GENERATED ALWAYS AS IDENTITY` | Generated | Generated | Error ORA-32795 | Error ORA-32795 |
| `GENERATED BY DEFAULT AS IDENTITY` | Generated | Generated | Accepted | Error ORA-01400 |
| `GENERATED BY DEFAULT ON NULL AS IDENTITY` | Generated | Generated | Accepted | Generated |
If you write only GENERATED AS IDENTITY, Oracle uses ALWAYS. Every identity column is implicitly NOT NULL, whichever mode you pick. You do not need to add the constraint yourself.
GENERATED ALWAYS
ALWAYS is the strictest mode. Oracle owns the value, and no INSERT can override it. Use it for surrogate keys, meaning keys with no business meaning, when you want a guarantee that every value came from the generator.
CREATE TABLE ticket_always (
ticket_id NUMBER GENERATED ALWAYS AS IDENTITY,
title VARCHAR2(100) NOT NULL,
CONSTRAINT ticket_always_pk PRIMARY KEY (ticket_id)
);
-- Works: the column is left out.
INSERT INTO ticket_always (title) VALUES ('Printer is jammed');
-- Works: DEFAULT asks the generator explicitly.
INSERT INTO ticket_always (ticket_id, title) VALUES (DEFAULT, 'Monitor flickers');
-- Fails with ORA-32795: cannot insert into a generated always identity column.
INSERT INTO ticket_always (ticket_id, title) VALUES (100, 'Keyboard sticks');
-- Fails with ORA-32796: cannot update a generated always identity column.
UPDATE ticket_always SET ticket_id = 500 WHERE title = 'Monitor flickers';The restriction also applies to UPDATE. Once a row exists, its ALWAYS identity value is fixed.
An INSERT with no column list also fails, because it supplies a value for every column, including the identity column. Always name the columns you insert into. That habit is a good idea in any case, because it keeps the statement working when someone adds a column later.
GENERATED BY DEFAULT
BY DEFAULT works like a column default. Oracle fills in the value only when you do not give one. You can supply your own value, which makes this mode useful for data migrations, for loading rows that must keep their legacy keys, and for tests that need known IDs.
CREATE TABLE ticket_default (
ticket_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
title VARCHAR2(100) NOT NULL,
CONSTRAINT ticket_default_pk PRIMARY KEY (ticket_id)
);
INSERT INTO ticket_default (title) VALUES ('Generated value'); -- ticket_id = 1
INSERT INTO ticket_default (ticket_id, title) VALUES (50, 'Chosen value'); -- ticket_id = 50
-- Fails with ORA-01400: cannot insert NULL into ticket_id.
INSERT INTO ticket_default (ticket_id, title) VALUES (NULL, 'Null value');The rejected NULL surprises many people. In BY DEFAULT mode the generator runs only when the column is absent from the statement or set to DEFAULT. A NULL is a supplied value, and the implicit NOT NULL rejects it.
The collision problem
An explicit value does not advance the underlying sequence. The generator knows nothing about the values you inserted by hand. Sooner or later it produces a number that already exists:
CREATE TABLE ticket_clash (
ticket_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
title VARCHAR2(100) NOT NULL,
CONSTRAINT ticket_clash_pk PRIMARY KEY (ticket_id)
);
INSERT INTO ticket_clash (ticket_id, title) VALUES (1, 'Loaded by hand');
-- The generator's first value is also 1.
-- Fails with ORA-00001: unique constraint (TICKET_CLASH_PK) violated.
INSERT INTO ticket_clash (title) VALUES ('Generated');The error is raised against a constraint you named, so the message tells you which table is involved. This is one reason to name constraints.
After a bulk load of explicit keys, move the generator past the highest existing value:
ALTER TABLE ticket_clash
MODIFY (ticket_id GENERATED BY DEFAULT AS IDENTITY (START WITH LIMIT VALUE));START WITH LIMIT VALUE tells Oracle to restart the generator at the current maximum of the column plus the increment. It works for BY DEFAULT and ALWAYS columns. Run it again after each further bulk load of explicit values.
GENERATED BY DEFAULT ON NULL
BY DEFAULT ON NULL accepts explicit values like BY DEFAULT, but it also treats a NULL as a request for a generated value. The NULL case matters in practice. Frameworks, ORMs, and bulk-loading tools often send every column in every statement, and they send NULL for a key they have not assigned. With plain BY DEFAULT those statements fail. With ON NULL they work.
CREATE TABLE ticket_on_null (
ticket_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
title VARCHAR2(100) NOT NULL,
CONSTRAINT ticket_on_null_pk PRIMARY KEY (ticket_id)
);
INSERT INTO ticket_on_null (ticket_id, title) VALUES (NULL, 'Generated from NULL'); -- 1
INSERT INTO ticket_on_null (ticket_id, title) VALUES (10, 'Chosen value'); -- 10
INSERT INTO ticket_on_null (title) VALUES ('Column omitted'); -- 2The ON NULL rule applies only to INSERT. The column is still NOT NULL, so this statement fails with ORA-01407:
UPDATE ticket_on_null SET ticket_id = NULL WHERE title = 'Chosen value';Explicit values cause the same collision problem here as in plain BY DEFAULT.
ON NULL is also available for ordinary, non-identity columns, as part of a DEFAULT ON NULL clause. The identity form is the same idea applied to the generator.
Choosing a mode
Start from who is allowed to write the key.
- Use
ALWAYSwhen only the database should create the key. It prevents accidental or hostile overrides and makes the column trustworthy as a surrogate key. - Use
BY DEFAULTwhen some code paths must supply keys, such as migrations, data copies between environments, or replication targets. Accept the duty to resynchronize the generator after explicit loads. - Use
BY DEFAULT ON NULLwhen the client may sendNULLfor the key, or when you want a table to accept both generated and supplied keys without errors.
A table can start in one mode and move to another. This is useful when ALWAYS blocks a one-off data load:
-- Relax the mode for a migration.
ALTER TABLE ticket_always
MODIFY (ticket_id GENERATED BY DEFAULT ON NULL AS IDENTITY);
-- ... load rows with explicit keys, then resynchronize ...
ALTER TABLE ticket_always
MODIFY (ticket_id GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE));
-- Restore the strict mode.
ALTER TABLE ticket_always
MODIFY (ticket_id GENERATED ALWAYS AS IDENTITY);Changing the mode on a live table is a schema change. Other sessions can insert while the table is relaxed, so do this in a maintenance window if the key must stay controlled.
Checking the mode in the data dictionary
USER_TAB_IDENTITY_COLS reports ALWAYS or BY DEFAULT in its GENERATION_TYPE column. It does not show ON NULL there. That flag is stored in USER_TAB_COLUMNS.DEFAULT_ON_NULL.
SELECT i.table_name,
i.column_name,
i.generation_type,
c.default_on_null
FROM user_tab_identity_cols i
JOIN user_tab_columns c
ON c.table_name = i.table_name
AND c.column_name = i.column_name
WHERE i.table_name LIKE 'TICKET%'
ORDER BY i.table_name;For TICKET_ON_NULL you should see BY DEFAULT with YES. For TICKET_DEFAULT you should see BY DEFAULT with NO.
Common mistakes
- Expecting
NULLto work with plainBY DEFAULT. It raises ORA-01400. UseON NULLor leave the column out of the statement. - Inserting without a column list into an
ALWAYStable. The statement supplies a value for the identity column and fails with ORA-32795. - Loading explicit keys and forgetting the generator. The next generated value collides with an existing key and raises ORA-00001. Use
START WITH LIMIT VALUEafterwards. - Treating identity values as gap-free. Rolled-back inserts, cache loss, and failed statements all consume values. The mode does not change this. The
CACHEoption, covered later in this tutorial, affects how many numbers can be lost.
Exercises
Exercise
A table has id NUMBER GENERATED BY DEFAULT AS IDENTITY. An application sends INSERT INTO t (id, name) VALUES (:id, :name) and binds NULL for :id when it has no key. What happens, and what is the smallest change to the table that makes the application work?
Show answer
The insert fails with ORA-01400, because in plain BY DEFAULT mode a supplied NULL is not replaced by a generated value and the identity column is implicitly NOT NULL. The smallest change is ALTER TABLE t MODIFY (id GENERATED BY DEFAULT ON NULL AS IDENTITY);, after which a NULL bind value makes Oracle generate the key.
Exercise
You migrated 200 rows with explicit keys 1 to 200 into a GENERATED BY DEFAULT AS IDENTITY table whose generator is still at its starting value of 1. The first normal insert after the migration fails with ORA-00001. Why, and how do you fix it without dropping the table?
Show answer
Explicit values do not advance the identity sequence, so the generator's first value, 1, already exists in the primary key. Run ALTER TABLE t MODIFY (id GENERATED BY DEFAULT AS IDENTITY (START WITH LIMIT VALUE));. Oracle then restarts the generator after the current maximum, so the next generated key is 201.
Exercise
Which dictionary views tell you that a column is GENERATED BY DEFAULT ON NULL, and what does each one show?
Show answer
USER_TAB_IDENTITY_COLS shows that the column is an identity column and reports GENERATION_TYPE as BY DEFAULT. USER_TAB_COLUMNS shows DEFAULT_ON_NULL = 'YES' for the same column. You need both to tell BY DEFAULT ON NULL apart from plain BY DEFAULT.