Re: Referential integrity broken (8.0.3), sub-select help

From: Patrick JACQUOT <patrick(dot)jacquot(at)anpe(dot)fr>
To:
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Referential integrity broken (8.0.3), sub-select help
Date: 2006-03-22 09:01:23
Message-ID: 44211263.5020807@anpe.fr
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

ogjunk-pgjedan(at)yahoo(dot)com wrote:

>Hello,
>
>I've got 2 tables, "url" (U), and "bookmark" (B), with "bookmark" pointing to "url" via FK.
>Somehow I ended up with some rows in B referencing non-existent rows in U.
>This sounds super strange and dangerous to me, and it's not clear to me how/why PG let this happen.
>I'm using 8.0.3.
>
>Here are the table references I just mentioned:
>
>Table "bookmark":
> id SERIAL
> CONSTRAINT pk_bookmark_id PRIMARY KEY
>
> Table "url":
> url_id INTEGER
> CONSTRAINT fk_bookmark_id REFERENCES bookmark(id)
>
>
>
Your DDL doesn't say : "B references U", but the contrary : "U
references B".
So it's perfectly right that somes tuples in B are not referenced by
tuples in U.
Please correct your constraints.

>Problem #1: Strange that PG allowed this to happen. Maybe my DDL above allows this to happen and needs to be tightened? I thought the above would ensure referential integrity, but maybe I need to specify something else?
>
>Problem #2: I'd like to find all rows in B that point to non-existent rows in U. I can do it with the following sub-select, I believe, but it's rather inefficient (EXPLAIN shows both tables would be sequentially scanned):
>
> SELECT * FROM bookmark WHERE id NOT IN (SELECT b.id FROM bookmark b, url u WHERE b.url_id=u.id);
>
>Is there a more efficient way to get the rows from "bookmark"?
>
>Thanks,
>Otis
>
>
>---------------------------(end of broadcast)---------------------------
>TIP 6: explain analyze is your friend
>
>
>
I think, for that one Scott's answer is OK
You could also try SELECT * FROM url U WHERE NOT EXISTS(SELECT * FROM
bookmark B WHERE B.url-id=U.id)
and see wich one is faster

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message ivan marchesini 2006-03-22 11:18:51 COPY tablename FROM and null values
Previous Message Aftab Alam 2006-03-22 03:38:47 Re: Power cut and performance problem