Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to remove orphan rows?

Tags:

mysql

I have a table with a lot of history entries that contain customer IDs.

There is a separate customer table. Occasionally some of the customer entries are removed.

Is there an easy way, without looping through each history entry, to drop all rows in the history table where the customer ID no longer exists because the customer row was deleted?

like image 583
p9807 Avatar asked Jun 22 '11 20:06

p9807


People also ask

How do I stop orphan records in SQL?

In SQL Server the correct way to avoid orphaned rows is to use DRI (Declared Referential Integrity) also known as foreign key constraints. When using DRI you can define what you want to happen when you update/delete a parent row(CASCADE options).

What is orphan records in database?

An orphan record is an imported transaction record that does not specify a site. To create a Maximo® database record from an imported record, you must specify a site on the transaction record.


3 Answers

delete from history_table where customer_id not in (select customer_id from customers)

did you mean something like this?

like image 187
heximal Avatar answered Oct 21 '22 22:10

heximal


DELETE h.* FROM history h
LEFT JOIN customer c ON h.customer_id = c.id
WHERE c.id IS NULL

I'm typing this from the top of my head, but you get the idea hopefully.

Delete syntax documentation

like image 38
Aistina Avatar answered Oct 22 '22 00:10

Aistina


How about:

DELETE FROM history_table 
WHERE customer_id NOT IN (SELECT customer_id FROM customer);
like image 6
Gerrat Avatar answered Oct 21 '22 23:10

Gerrat