X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 0F62C11F6C39 for ; Wed, 12 Apr 2006 22:11:32 -0300 (ADT) X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Score: 0.121 X-Spam-Level: X-Spam-Status: No, score=0.121 required=5 tests=[AWL=0.120, UNPARSEABLE_RELAY=0.001] Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id t5f9euHymEC3 for ; Wed, 12 Apr 2006 22:11:20 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from ll.mit.edu (LLMAIL.LL.MIT.EDU [129.55.12.40]) by postgresql.org (Postfix) with ESMTP id 92A2E11F6B4A for ; Wed, 12 Apr 2006 22:11:21 -0300 (ADT) Received: (from smtp@localhost) by ll.mit.edu (8.12.10/8.8.8) id k3D1BNqZ005994 for ; Wed, 12 Apr 2006 21:11:23 -0400 (EDT) Received: from UNKNOWN( ), claiming to be "sty.llan" via SMTP by llmail, id smtpdAAAWaaOPl; Wed Apr 12 21:11:19 2006 Date: Wed, 12 Apr 2006 21:11:18 -0400 From: George Young To: pgsql-sql@postgresql.org Subject: trigger to enforce FK with nulls? Message-Id: <20060412211118.05411612.gry@ll.mit.edu> Organization: MIT Lincoln Laboratory X-Mailer: Sylpheed version 2.2.4 (GTK+ 2.8.0; i686-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Archive-Number: 200604/85 X-Sequence-Number: 24894 [PostgreSQL 8.1.3 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 4.0.1] I'm starting to use lots of foreign key constraints to keep my data clean. In one case, however, I need to allow null values for the key. E.g.: create table opset_steps(opset text, step text, step_num int); create table steps(run text, step text, opset text, user text, step_num int); The constraint on steps should be: steps.(opset,step) must be found in opset_steps.(opset,step) UNLESS steps.opset is null. I started to put dummy rows in opset_steps with opset='NO-OPSET' for each step with no real opset, but this looks really kludgy. Since foreign keys per se can't do this, I presume the way is to use triggers, though I have not used triggers before. Any suggestions, caveats? Opset_steps has only 4400 rows, and inserts to steps are not real frequent, so I don't *think* performace should be a problem. No updates are ever made to steps.opset and steps.step, or to opset_steps.(opset,step) [though updates are often made to *other* fields of steps]. -- George Young -- "Are the gods not just?" "Oh no, child. What would become of us if they were?" (CSL)