Sub topic 3
ALWAYS vs BY DEFAULT vs BY DEFAULT ON NULL
An identity column generates its own key values. The clause after GENERATED controls what happens when an INSERT also supplies a value. This chapter assumes basic INSERT syntax, the departments and employees tables from earlier chapters, and Oracle 12c or later.
Choosing an identity mode
GENERATED ALWAYS: Oracle rejects any explicit value with ORA-32795.GENERATED BY DEFAULT: Oracle uses an explicit value. An explicit NULL fails with ORA-01400.GENERATED BY DEFAULT ON NULL: Oracle uses an explicit value. An explicit NULL becomes the next generated value.
-- Fails with ORA-32795: the column is GENERATED ALWAYS.
INSERT INTO departments (department_id, department_name) VALUES (99, 'Support');
-- Accepted: BY DEFAULT ON NULL keeps 5000 and generates a value for NULL.
INSERT INTO employees (employee_id, email) VALUES (5000, '[email protected]');
INSERT INTO employees (employee_id, email) VALUES (NULL, '[email protected]');Linking tables with FOREIGN KEY and ON DELETE
A foreign key requires each child value to match a parent key. The ON DELETE clause sets what happens to child rows when a parent row is deleted. CASCADE deletes the child rows, SET NULL clears the foreign key column, and omitting the clause blocks the parent delete while children exist. Oracle has no ON UPDATE action.
Tuning identity columns
START WITH sets the first value, and INCREMENT BY sets the step. CACHE n keeps n values in memory for speed. If the instance stops, unused cached values are lost, so gaps can appear. Do not rely on identity values for ordering or for a gap-free sequence.
Managing constraints with ALTER TABLE
ALTER TABLE employees ADD (manager_id NUMBER);
ALTER TABLE employees ADD CONSTRAINT employees_manager_fk
FOREIGN KEY (manager_id) REFERENCES employees (employee_id)
DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE employees DISABLE CONSTRAINT employees_dept_fk;
ALTER TABLE employees ENABLE NOVALIDATE CONSTRAINT employees_dept_fk;
ALTER TABLE employees DROP CONSTRAINT employees_manager_fk;Constraint states control enforcement:
ENABLE VALIDATE(the default) checks new rows and existing rows.ENABLE NOVALIDATEchecks new rows only.DISABLEskips checks entirely.DEFERRABLE INITIALLY DEFERREDpostpones the check untilCOMMIT.
Inspecting the data dictionary
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;Exercise
The departments table uses GENERATED ALWAYS. A script inserts (departmentid, departmentname) = (NULL, 'Legal'). What happens, and how would you change the table so the script works?
Show answer
Oracle raises ORA-32795 because ALWAYS rejects any explicit value, including NULL. Change the column to GENERATED BY DEFAULT ON NULL AS IDENTITY, or change the script to omit department_id from the column list.