Received: from makus.postgresql.org (makus.postgresql.org [98.129.198.125]) by mail.postgresql.org (Postfix) with ESMTP id 1DD4414E1F38 for ; Thu, 2 Aug 2012 20:23:49 -0300 (ADT) Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1Sx4k7-0006LZ-Mf for pgsql-sql@postgresql.org; Thu, 02 Aug 2012 23:23:48 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.5/8.14.5) with ESMTP id q72NNYce029694; Thu, 2 Aug 2012 19:23:35 -0400 (EDT) From: Tom Lane To: Wayne Cuddy cc: PostgreSQL Subject: Re: can this be done with a check expression? In-reply-to: <20120802231043.GA16173@slacker.ja10629.home> References: <20120802231043.GA16173@slacker.ja10629.home> Comments: In-reply-to Wayne Cuddy message dated "Thu, 02 Aug 2012 19:10:43 -0400" Date: Thu, 02 Aug 2012 19:23:34 -0400 Message-ID: <29693.1343949814@sss.pgh.pa.us> X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201208/3 X-Sequence-Number: 36774 Wayne Cuddy writes: > I have a table with 3 columns: > name text > start_id integer > end_id integer > start_id and end_id are ranges which must not overlap but can have gaps > between them. Is it possible to formulate a table check constraint that > can verify that either id does not fall within an existing range at > insert time? IE prevent overlaps during insert? You can't do it reliably with a check constraint, at least not short of taking table-wide locks to serialize all modifications of the table. (If you were willing to do that, a check constraint calling a function that does an EXISTS probe would work; although personally I'd use a trigger instead. Either way, performance is likely to suck.) A less bogus way of doing things is to use an EXCLUDE constraint, although that will restrict you to be running PG 9.0 or newer. You also need some way of representing the ranges as indexable objects. In 9.0 or 9.1, probably the best way is to use contrib/seg/ to represent the ranges as line segments. 9.2 will have a cleaner solution, ie range types. regards, tom lane