Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting orphans from a table

I am trying to clean up a table where there are quite a few orphaned items.

I am approaching this by checking to see if there is a relationship to another table by looking for null values.

   DELETE FROM table1 
LEFT JOIN table2 ON table1.ID = table2.ID
    WHERE table2.ID IS NULL

I get an error that the left outer join is not valid.

I am looking for suggestions on other ways that I can delete these orphans from this broken relationship

like image 330
Brad Avatar asked Jul 03 '11 16:07

Brad


People also ask

How do I remove a dependencies from a table in SQL?

Right-click a database in SQL Server Object Explorer, and select Delete. Accept all the default settings in the Delete Database dialog, and click OK.

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 does delete from Table_name do?

The DELETE statement is used to delete existing records in a table.

Can we delete data from parent table?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted.


2 Answers

If you want to use the same syntax, here is how it could have been:

DELETE a 
FROM table1 a  
LEFT JOIN table2 b 
ON a.id = b.id 
WHERE b.id IS NULL 
like image 176
t-clausen.dk Avatar answered Nov 01 '22 02:11

t-clausen.dk


try this:

DELETE  FROM        table1
WHERE NOT EXISTS (SELECT NULL FROM table2 WHERE table1.ID = table2.ID)
like image 38
Maziar Taheri Avatar answered Nov 01 '22 01:11

Maziar Taheri