Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ON DELETE SET NULL in postgres

HI I'm new to postgresql environment so been lost for a while. I want to keep my data when parent entity is deleted. I want to know how to make 'ON DELETE SET NULL' for postgresql database. Please give me a clue.

like image 550
tamikoon Avatar asked Nov 11 '13 03:11

tamikoon


People also ask

What is on delete Set null?

A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to NULL. The records in the child table will not be deleted in SQL Server.

What is the difference between Cascade delete and set null on delete?

ON DELETE CASCADE : SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table. ON DELETE SET NULL : SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted.

Why is my foreign key null?

A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.

What does on delete No action do?

For an ON DELETE or ON UPDATE that is not specified, the default action is always NO ACTION . As the default, an ON DELETE NO ACTION or ON UPDATE NO ACTION clause that is specified explicitly does not appear in SHOW CREATE TABLE output or in tables dumped with mysqldump.


1 Answers

ON DELETE SET NULL is a standard foreign key constraint option.

CREATE TABLE some_child (     parent_id integer references parent(id) on delete set null ); 

or:

ALTER TABLE some_child  ADD CONSTRAINT parent_id_fk  FOREIGN KEY (parent_id) REFERENCES parent(id)  ON DELETE SET NULL; 

See the documentation.

In future posts make sure you include your PostgreSQL version and explain what you've already tried.

like image 55
Craig Ringer Avatar answered Sep 20 '22 12:09

Craig Ringer