Re: Check/unique constraint question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Scott Rohde <srohde(at)illinois(dot)edu>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Check/unique constraint question
Date: 2014-12-09 18:43:15
Message-ID: 7561.1418150595@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Scott Rohde <srohde(at)illinois(dot)edu> writes:
> 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.

Indeed, this illustrates perfectly why subqueries in CHECK constraints
are generally a Bad Idea: the constraint is no longer just about the
contents of one row but about its relationship to other rows, and that
makes the timing of checks relevant. Hiding the subquery in a function
doesn't do anything to resolve that fundamental issue.

The original example seemed to work for retail inserts because the check
gets applied before the row is physically inserted. It would fail on
updates though, or when trying to add the constraint after the fact.

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Scott Rohde 2014-12-09 22:06:59 Re: Check/unique constraint question
Previous Message Scott Rohde 2014-12-09 18:01:39 Re: Check/unique constraint question