Postgresql – Will FK ON UPDATE CASCADE work

constraintforeign keypostgresql

Intuitively, adding the option ON UPDATE CASCADE to a foreign key constraint will have the effect of updating all referencing columns with the updated value of the key. Would that really work?

Example lifted from manual:

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    shipping_address text,
    ...
);

CREATE TABLE order_items (
    product_no integer REFERENCES products ON DELETE RESTRICT,
    ## HERE'S THE LINE THAT I MODIFIED FROM THE MANUAL, IT USED TO SAY 'ON DELETE CASCADE'
    order_id integer REFERENCES orders ON UPDATE CASCADE,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);

I am using Postgres 9.1.

Best Answer

Possible options for the ON DELETE and ON UPDATE clauses are explained in the CREATE TABLE page of the manual.

The default is NO ACTION, so if you have any foreign keys defined without explicitly specifying what action to be performed on updates of the referenced primary or unique key, it is the same as if ON UPDATE NO ACTION was specified:

NO ACTION

Produce an error indicating that the deletion or update would create a foreign key constraint violation. If the constraint is deferred, this error will be produced at constraint check time if there still exist any referencing rows. This is the default action.


If you have specified ON UPDATE CASCADE on a foreign key, the referencing rows will be updated accordingly when a referenced row is updated:

CASCADE

Delete any rows referencing the deleted row, or update the value of the referencing column to the new value of the referenced column, respectively.

Primary keys are usually not updated (and for good reasons) but there are situations where it can be useful. Plus, the foreign key may be referencing not a primary key but a (rarely updated) unique key.