Re: How to use a cross column exclude constraint - Mailing list pgsql-novice

From David G. Johnston
Subject Re: How to use a cross column exclude constraint
Date
Msg-id CAKFQuwb+eL7bYaE_9b9t7mGGj=c5SCYPmP0UoWitc86=+1UnCQ@mail.gmail.com
Whole thread Raw
In response to Re: How to use a cross column exclude constraint  (chidamparam muthusamy <mchidamparam@gmail.com>)
Responses Re: How to use a cross column exclude constraint
List pgsql-novice
On Tue, Aug 23, 2022 at 7:48 AM chidamparam muthusamy <mchidamparam@gmail.com> wrote:

CREATE TABLE products (    product_no integer,    name text,    price numeric CHECK (price > 0),    discounted_price numeric CHECK (discounted_price > 0),    CHECK (price > discounted_price)
);
In the above example, column 'discounted_price'  value is checked that it should be less than the column value, 'price'.
Is it possible to add similar check condition for the columns, 'record_a_id' and 'record_b_id' that is
CHECK(record_a_id != record_b_id)


The declarative constraints available do not allow for a "diagonal" definition.  CHECK constraints are row-limited but can reference any columns.  Exclusion constraints are column-oriented, the specified columns are compared to the same columns in all other rows.

You cannot declare that a value in column b exists or does not exist in column a on a different row.  You can write a trigger to that effect if you'd like.

The absence of a declarative feature for this is because this model is non-normalized and the features of SQL are generally designed to help implement normalized data models.  You should consider whether you can redesign things so that you can leverage the features present in the language; and the efficiencies and robustness that such features tend to have that custom trigger code may lack.

David J.

pgsql-novice by date:

Previous
From: chidamparam muthusamy
Date:
Subject: Re: How to use a cross column exclude constraint
Next
From: awolchute@tutanota.com
Date:
Subject: Re: How to use a cross column exclude constraint