mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Check Table For Any Orphaned Records as a postgres til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_852 TILs and counting..._
|
||||
_853 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -391,6 +391,7 @@ _852 TILs and counting..._
|
||||
- [Between Symmetric](postgres/between-symmetric.md)
|
||||
- [Capitalize All The Words](postgres/capitalize-all-the-words.md)
|
||||
- [Change The Current Directory For psql](postgres/change-the-current-directory-for-psql.md)
|
||||
- [Check Table For Any Oprhaned Records](postgres/check-table-for-any-orphaned-records.md)
|
||||
- [Checking Inequality](postgres/checking-inequality.md)
|
||||
- [Checking The Type Of A Value](postgres/checking-the-type-of-a-value.md)
|
||||
- [Clear The Screen In psql](postgres/clear-the-screen-in-psql.md)
|
||||
|
||||
27
postgres/check-table-for-any-orphaned-records.md
Normal file
27
postgres/check-table-for-any-orphaned-records.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Check Table For Any Orphaned Records
|
||||
|
||||
If you don't have a foreign key constraint in place to enforce the relationship
|
||||
between records in two different tables, then there are a number of ways you
|
||||
could end up with orphaned records. Orphaned records are records that have a
|
||||
value in an `*_id` column when that value doesn't correspond to any record in
|
||||
the related table.
|
||||
|
||||
For example, let's say we have an `authors` table with an `id` column and a
|
||||
`books` table with an `author_id` column. If there is a book record with an
|
||||
`author_id` value that doesn't resolve to any record in the `authors` table,
|
||||
then that book is an orphaned record.
|
||||
|
||||
You can find out if a table has orphaned records like so:
|
||||
|
||||
```sql
|
||||
select count(*)
|
||||
from books
|
||||
left join authors
|
||||
on books.author_id = authors.id
|
||||
where authors.id is null
|
||||
and books.author_id is not null;
|
||||
```
|
||||
|
||||
We select from our table with the foreign key (`books`) and _left join_ it
|
||||
against the related table (`authors`). If there are any book records where the
|
||||
joined author row is `null`, then that book is orphaned.
|
||||
Reference in New Issue
Block a user