Re: Are circular REFERENCES possible ?

From: "Josh Berkus" <josh(at)agliodbs(dot)com>
To: Denis Bucher <dbucher(at)niftycom(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Are circular REFERENCES possible ?
Date: 2001-08-07 15:01:45
Message-ID: web-97958@davinci.ethosmedia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Denis,

> I have a case where I wanted to do circular REFERENCES, is this
> impossible ?

It can be done. It's just a bad idea.

> We deliver to the *shops* of our *customers*.
> We have therefore two tables :
> - customers (enterprise, financial information, and so on...)
> - shop (with a name, street, phone number, name of manager)
>
> Now, each shop REFERENCES a customer so that we know
> to which customer belongs a shop.
>
> AND, each customer has a DEFAULT shop for deliveries, i.e. most
> customers only have one shop, or a main shop and many small ones.
> Therefore a customer should REFERENCES the 'main' or 'default' shop.

You can do this by applying the constraints *after* table creation.
However, you will forever fight the following problems:

1. You will not be able to add any records to Customers without dropping
and re-creating the REFERENCES each time.
2. You will never be able to delete a record from either table due to
the circular reference check.
3. Some UPDATES will also fail for the same reason.

All of this makes circular references a bad idea; references are meant
to be heirarchical. Heck, I got into a real mess when I accidentally
set up a circular reference among 5 tables ... took me forever to figure
out why INSERTS kept failing.

So, an alternate solution to your database structure:

1. Each Customer has one to many Shops (Shops.CustomerID REFERENCES
Customers(ID)).
2. Each Shop has a Boolean characteristic Default.
3. Of a Customer's shops, only one can have Default=TRUE at any one
time.

You use triggers or functions to enforce rule 3. This system works
quite well for this purpose ... I was able to put it to use for a much
more complex CRM system with main and secondary HR and billing
addresses.

Your third alternative is to create a JOIN table called Default Shops.
However, this does not really provide you any additional referential
integrity -- it jsut may suit you if you find triggers intimidating.

-Josh

______AGLIO DATABASE SOLUTIONS___________________________
Josh Berkus
Complete information technology josh(at)agliodbs(dot)com
and data management solutions (415) 565-7293
for law firms, small businesses fax 621-2533
and non-profit organizations. San Francisco

Attachment Content-Type Size
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2001-08-07 15:38:08 Re: Re: Adding an INTERVAL to a variable
Previous Message Vivek Khera 2001-08-07 15:00:23 Re: Adding an INTERVAL to a variable