1

I was trying to understand the concept of orphaned rows in a database and how they can be found and removed.

Say for example you had 2 tables (person,dog) and there was a 1-to-1 relationship between them so every person must have a dog and every dog must have an owner.

Person table:

 ID      Name   
 1       James
 2       Matt
 3       Mike   

Dog table:

 ID Name Owner_id
 1   Sam    1
 2   Rex    2
 3   Max    3
 4   Fred   4

Now if i joined those tables with:

 SELECT *
 FROM Person P
 FULL OUTER JOIN Dog D ON P.id = D.Owner_id 

This would produce a result where dog (fred) doesnt have an owner and just appears as NULL.

Is this therefore an orphaned row as it should have a matching owner?

Is this only caused due to no primary/foreign keys?

How can orphaned rows been found in a database?

Ryan Gadsdon
  • 2,272
  • 4
  • 31
  • 56

1 Answers1

9

You sort of answered your own question. But I would use the following left join to find the orphaned rows:

SELECT d.*
FROM Dog d
LEFT JOIN Person p
    ON d.Owner_id = p.ID
WHERE
    p.ID IS NULL;

This would return every dog record which does not have a matching owner.

One way to avoid situations like this would be to employ foreign key constraints(like, Cascade Delete - link). With such constraints it would not be possible to delete an owner record if certain dog records were still referencing that owner.

I hope that this answer helps you to avoid barking up the wrong tree (woof).

Ritveak
  • 2,930
  • 2
  • 13
  • 28
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360