Skip to Main Content
  • Questions
  • Why does Oracle allow ON DELETE SET NULL while creating FOREIGN KEY on a NOT NULL column?

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Sachin.

Asked: October 08, 2024 - 4:38 pm UTC

Last updated: October 10, 2024 - 12:51 pm UTC

Version: 23ai

Viewed 1000+ times

You Asked

Hi Team,

Need your help understanding Oracle DB's philosophy in the following code.
What purpose does the "ON DELETE SET NULL" serve here?

Code:
CREATE TABLE IF NOT EXISTS t1(
    c1 NUMBER,
    c2 VARCHAR2(255),
    CONSTRAINT pkey_t1 
    PRIMARY KEY(c1)
);

CREATE TABLE IF NOT EXISTS t2(
    c1 NUMBER NOT NULL,  --  Why does not Oracle complain about this
    c2 VARCHAR2(255),
    CONSTRAINT fkey_t2 
    FOREIGN KEY(c1) 
    REFERENCES t1(c1) 
    ON DELETE SET NULL   --+ or this?
);

INSERT INTO t1 VALUES(1000,'Referenced-Record-1');
INSERT INTO t2 VALUES(1000,'Referencing-Record-1');

DELETE FROM t1 WHERE c1 = 1000;


Output of the DELETE statement:
SQL Error: ORA-01407: cannot update ("T2"."C1") to NULL
01407. 00000 - "cannot update (%s) to NULL"


Note: I have tested the same functionality on MySQL and it clearly complains about it - "Column 'c1' cannot be NOT NULL: needed in a foreign key constraint 't2_ibfk_1' SET NULL".
Shouldn't Oracle also tell something similar?

and Chris said...

Think about this:

Let's say you want to make an optional column mandatory. It currently has an FK on it with ON DELETE SET NULL.

If the column must be nullable to use SET NULL, you have to recreate the FK too (you can't modify the ON DELETE clause for FKs) without SET NULL to make the column mandatory.

Is that the behaviour you want?

I'm not saying this is necessarily why Oracle Database allows mandatory columns to have SET NULL FKs - I honestly don't know why this decision was made. Possibly it's just something that was overlooked or too low priority to be implemented.

They are separate constraints though; allowing them to be set in conflicting ways can be useful in some cases.