Skip site navigation (1) Skip section navigation (2)

Re: How to find out whether a row is currently referenced by a row in a different table?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: slapo(at)centrum(dot)sk
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: How to find out whether a row is currently referenced by a row in a different table?
Date: 2010-07-01 15:07:10
Message-ID: 4865.1277996830@sss.pgh.pa.us (view raw or flat)
Thread:
Lists: pgsql-novice
<slapo(at)centrum(dot)sk> writes:
> does anyone know how to find out whether a row is currently referenced by a row in a different table?They are bound together by a foreign key constraint.
> The reason why I would like to know this is that I would like to be able to delete rows only if they aren't used anywhere.

Well, you could try to delete the row and see if it succeeds ...

> It occurred to me that I could create a function that would query a system table for all references to the table the row would be deleted from and then scan tables that refer to that one, but I was hoping there would be a simpler and maybe a more efficient way to do this.

This is a good recipe for shooting yourself in the foot.  You can *not*
rely on scanning dependent tables for matching rows, because any attempt
to do that will miss just-inserted rows that haven't been committed yet.
(The FK mechanism has some special interlocking abilities to deal with
race conditions like that, but you can't get at those from SQL.)

The only way you could reliably do it "manually" would be to lock all
the dependent tables against modifications, which would pretty much
destroy any concurrency you might have.

			regards, tom lane

In response to

pgsql-novice by date

Next:From: Atif JungDate: 2010-07-01 16:30:28
Subject: Re: AUTO COMMIT
Previous:From: slapoDate: 2010-07-01 12:29:03
Subject: How to find out whether a row is currently referenced by a row in a different table?

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group