Re: Will PG use composite index to enforce foreign keys?

From: "Scott Marlowe" <scott(dot)marlowe(at)gmail(dot)com>
To: "John Burger" <john(at)mitre(dot)org>
Cc: "PostgreSQL General" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Will PG use composite index to enforce foreign keys?
Date: 2007-12-01 03:43:59
Message-ID: dcc563d10711301943r5ec5e84bv7a7c9bf8de35a3a3@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Nov 29, 2007 10:51 AM, John Burger <john(at)mitre(dot)org> wrote:
> Hi -
>
> I know that the foreign key machinery will use an index on the
> referring column if one exists. My question is whether it will use a
> composite index? For instance:
>
> create table allLemmaSenseMap (
> wordID integer references allLemmas,
> senseID integer references allSenses,
> primary key (wordID, senseID)
> );
>
> If I delete something from allLemmas, will the FK check use the PK
> index above? (I know I should at least have an index on senseID as
> well, because of the other foreign key.)

Yes. It will

> As a secondary question, is there any way I could have answered this
> myself, using analyze, the system catalogs, etc? ANALYZE DELETE
> doesn't seem to show the FK checking that must go on behind the scenes.

You could have coded up an example to see if it worked I guess.
Here's a short example:

create table a (i int, j int, info text, primary key (i,j));
create table b (o int, p int, moreinfo text, foreign key (o,p) references a);
insert into a values (1,2,'abc');
insert into b values (1,2,'def');
INSERT 0 1
insert into b values (1,3,'def');
ERROR: insert or update on table "b" violates foreign key constraint "b_o_fkey"
DETAIL: Key (o,p)=(1,3) is not present in table "a".
delete from a;
ERROR: update or delete on table "a" violates foreign key constraint
"b_o_fkey" on table "b"
DETAIL: Key (i,j)=(1,2) is still referenced from table "b".

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2007-12-01 03:48:57 Re: power failure....
Previous Message Tom Allison 2007-12-01 00:49:52 power failure....