Re: FOREIGN KEY questions

From: Stephan Szabo <sszabo(at)megazone23(dot)bigpanda(dot)com>
To: Neil Conway <nconway(at)klamath(dot)dyndns(dot)org>
Cc: PostgreSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: FOREIGN KEY questions
Date: 2000-09-10 21:29:25
Message-ID: Pine.BSF.4.10.10009101423570.8215-100000@megazone23.bigpanda.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Sun, 10 Sep 2000, Neil Conway wrote:

> One database has a group of tables with intereferential data.
> For example:
>
> CREATE TABLE messages (
> /* ... */
> poster INT4 NOT NULL,
> thread INT4 NOT NULL
> );
>
> CREATE TABLE users (
> id serial
> /* ... */
> );
>
> CREATE TABLE threads (
> id serial
> /* ... */
> );
>
> messages.poster should refer to a valid (and unique) users.id - that
> is the person who posted the message. If there is no users.id with
> the same value as every messages.poster , there is a problem. The
> same applies to message.thread and threads.id .

Well, I'd suggest:
CREATE TABLE users (
id serial PRIMARY KEY,
/* ... */
);

CREATE TABLE threads (
id serial PRIMARY KEY,
/* ... */
);

CREATE TABLE messages (
/* ... */
poster int4 NOT NULL CONSTRAINT fk_message_poster REFERENCES users,
thread int4 NOT NULL CONSTRAINT fk_message_thread REFERENCES threads
);

> How do I check that this data is being entered correctly? Is this
> a situation where I should be using foreign keys? Or can this only
> be done with external logic (i.e. the application doing the inserts
> should check first that the data it's receiving is valid).

Yeah, something like the above should work. It'll also prevent you
from removing a user who has mesages or threads that have messages.
You can make it do other things in those cases, like delete the
messages that are associated with that user or thread by
adding (ON DELETE CASCADE) to each of the constraints.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Erich 2000-09-10 22:59:59 Help! How to find the definition of a user-defined function
Previous Message Neil Conway 2000-09-10 21:15:46 Re: triggers in SQL?