h1

A nice way to check if there are orphaned entries

September 5, 2007

In a database table that is linked to another, sometimes an entry gets deleted and the children of that entry don’t get deleted along with it. Use this little bit of SQL to check for these entries:
SELECT one.id
FROM one
WHERE one.other_id NOT IN (
SELECT other.id
FROM other);

This can then be modified to delete those entries by changing the SELECT one.id to DELETE, like this:
DELETE
FROM one
WHERE one.other_id NOT IN (
SELECT other.id
FROM other);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.