Sobes.tech
Junior — Middle

What database behavior of PostgreSQL is observed if no explicit action is specified when deleting a record that is linked to another table via a foreign key?

sobes.tech AI

Answer from AI

In PostgreSQL, if no explicit action is specified when deleting a record related to another table via a foreign key (for example, ON DELETE CASCADE or ON DELETE SET NULL), the default behavior is ON DELETE NO ACTION.

This means that an attempt to delete a record that is referenced from another table will result in a foreign key constraint error, and the deletion will not be performed.

Thus, the database prevents data integrity violations by not allowing the deletion of a parent record while related child records exist.

Example:

-- Orders table with a foreign key to the customers table
CREATE TABLE customers (
    id SERIAL PRIMARY KEY
);

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INT REFERENCES customers(id)
);

-- Attempt to delete a customer with existing orders without ON DELETE CASCADE
DELETE FROM customers WHERE id = 1; -- will cause an error

To allow deletion with automatic removal of related records, you need to explicitly specify ON DELETE CASCADE when creating the foreign key.

What database behavior of PostgreSQL is observed if… - sobes.tech