X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id A77B19FA621 for ; Sat, 1 Jul 2006 01:11:30 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 19945-07 for ; Sat, 1 Jul 2006 01:11:24 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 4AF229FA0EC for ; Sat, 1 Jul 2006 01:11:24 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.6/8.13.6) with ESMTP id k614BM98018960; Sat, 1 Jul 2006 00:11:22 -0400 (EDT) To: Richard Broersma Jr cc: General Postgresql List Subject: Re: Alternative to Select in table check constraint In-reply-to: <20060630215512.18287.qmail@web31813.mail.mud.yahoo.com> References: <20060630215512.18287.qmail@web31813.mail.mud.yahoo.com> Comments: In-reply-to Richard Broersma Jr message dated "Fri, 30 Jun 2006 14:55:12 -0700" Date: Sat, 01 Jul 2006 00:11:22 -0400 Message-ID: <18959.1151727082@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200607/1 X-Sequence-Number: 25575 Richard Broersma Jr writes: > The following codes doesn't work on PostgreSQL 8.1.4 but according to > the book does conform to SQL-92. > CHECK ( 1 = ALL ( SELECT COUNT(STATUS) > FROM BADGES > WHERE STATUS = 'A' > GROUP BY EMPNO)) Yeah, the spec does allow sub-SELECTs in CHECK constraints but PG doesn't implement that. The problem with it is that there's no clear way to make it perform reasonably, because the CHECK doesn't simply implicate the row you're currently inserting/updating --- every other row is potentially referenced by the sub-SELECT, and so changing row X might make the CHECK condition fail at row Y. A brute-force implementation would be that every update of any sort to BADGES causes us to re-evaluate the CHECK constraint (hence, re-scan BADGES entirely to compute the sub-SELECT) for every row of BADGES (hence, O(N^2) work if there are N rows in the table). That is certainly unworkable :-(. A bright person can think of ways to optimize particular cases but it's not easy to see how the machine might figure it out for arbitrary SELECTs. The unique-index hack that Michael suggested amounts to hand-optimizing the sub-SELECT constraint into something that's efficiently checkable. regards, tom lane