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 164679DC800 for ; Sun, 5 Mar 2006 06:07:48 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 67258-03 for ; Sun, 5 Mar 2006 06:07:49 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from fep02.ttnet.net.tr (mail.ttnet.net.tr [212.175.13.129]) by postgresql.org (Postfix) with ESMTP id D84EE9DC856 for ; Sun, 5 Mar 2006 06:07:44 -0400 (AST) Received: from alamut ([85.96.109.238]) by fep02.ttnet.net.tr with ESMTP id <20060305100527.FGLN7467.fep02.ttnet.net.tr@alamut>; Sun, 5 Mar 2006 12:05:27 +0200 Date: Sun, 5 Mar 2006 12:05:27 +0200 From: Volkan YAZICI To: Nikolay Samokhvalov Cc: pgsql-sql@postgresql.org, Jeff Frost Subject: Re: Check/unique constraint question Message-ID: <20060305100526.GA214@alamut> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.4.2.1i X-NAI-Spam-Rules: 1 Rules triggered BAYES_00=-2.5 X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=2.262 required=5 tests=[AWL=-0.536, DNS_FROM_RFC_ABUSE=0.479, DNS_FROM_RFC_POST=1.44, DNS_FROM_RFC_WHOIS=0.879, UPPERCASE_25_50=0] X-Spam-Score: 2.262 X-Spam-Level: ** X-Archive-Number: 200603/91 X-Sequence-Number: 24437 On Mar 05 12:02, Nikolay Samokhvalov wrote: > Unfortunately, at the moment Postgres doesn't support subqueries in > CHECK constraints I don't know how feasible this is but, it's possible to hide subqueries that will be used in constraints in procedures. Here's an alternative method to Nikolay's: CREATE TABLE where_check (active bool, id int); CREATE OR REPLACE FUNCTION check_id (bool, int) RETURNS bool AS ' SELECT CASE WHEN $1 THEN NOT EXISTS (SELECT 1 FROM where_check AS W WHERE W.active IS TRUE AND W.id = $2) ELSE TRUE END; ' LANGUAGE SQL; -- A partial index like -- CREATE INDEX active_id_idx ON where_check (id) -- WHERE active IS TRUE; -- should speed up above query ALTER TABLE where_check ADD CONSTRAINT idchk CHECK (check_id(active, id)); test=# INSERT INTO where_check VALUES (TRUE, 2); INSERT 0 1 test=# INSERT INTO where_check VALUES (FALSE, 2); INSERT 0 1 test=# INSERT INTO where_check VALUES (TRUE, 2); ERROR: new row for relation "where_check" violates check constraint "idchk" Regards.