Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1XyP6W-0003N8-9b for pgsql-sql@arkaria.postgresql.org; Tue, 09 Dec 2014 18:01:44 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1XyP6V-00030B-QK for pgsql-sql@arkaria.postgresql.org; Tue, 09 Dec 2014 18:01:43 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:DHE_RSA_AES_256_CBC_SHA256:256) (Exim 4.80) (envelope-from ) id 1XyP6V-000305-38 for pgsql-sql@postgresql.org; Tue, 09 Dec 2014 18:01:43 +0000 Received: from mwork.nabble.com ([162.253.133.43]) by makus.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1XyP6R-0004fO-Ns for pgsql-sql@postgresql.org; Tue, 09 Dec 2014 18:01:40 +0000 Received: from msam.nabble.com (unknown [162.253.133.85]) by mwork.nabble.com (Postfix) with ESMTP id 9CFE7D2632D for ; Tue, 9 Dec 2014 10:01:40 -0800 (PST) Date: Tue, 9 Dec 2014 11:01:39 -0700 (MST) From: Scott Rohde To: pgsql-sql@postgresql.org Message-ID: <1418148099196-5829778.post@n5.nabble.com> In-Reply-To: References: Subject: Re: Check/unique constraint question MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Pg-Spam-Score: -1.1 (-) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-sql Precedence: bulk Sender: pgsql-sql-owner@postgresql.org There is something a bit odd about this solution: If you start with an empty table, the constraint will allow you to do INSERT INTO foo (active, id) VALUES ('t', 5); But if you insert this row into the table first and /then/ try to add the constraint, it will complain that an existing row violates the constraint. This begs the question of when constraints are checked. I had always thought of constraints as being static conditions that (unlike some trigger condition that masquerades as a constraint) apply equally to existing rows and to rows you are about to add. This seems to show that not all constraints work this way. Nikolay Samokhvalov wrote > just a better way (workaround for subqueries in check constraints...): > > CREATE OR REPLACE FUNCTION id_is_valid( > val INTEGER > ) RETURNS boolean AS $BODY$ > BEGIN > IF val IN ( > SELECT id FROM foo WHERE active = TRUE AND id = val > ) THEN > RETURN FALSE; > ELSE > RETURN TRUE; > END IF; > END > $BODY$ LANGUAGE plpgsql; > ALTER TABLE foo ADD CONSTRAINT C_foo_iniq_if_true CHECK (active = > FALSE OR id_is_valid(id)); > > ... -- View this message in context: http://postgresql.nabble.com/Check-unique-constraint-question-tp2145289p5829778.html Sent from the PostgreSQL - sql mailing list archive at Nabble.com. -- Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-sql