Re: Validating check constraints without a table scan?

From: Philip Couling <couling(at)gmail(dot)com>
To: jian he <jian(dot)universality(at)gmail(dot)com>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Validating check constraints without a table scan?
Date: 2024-11-20 11:16:20
Message-ID: CANWftzLezTEGwGr=dVRKMvQ0mWqcudV_EbtywFHEetynGuX6KA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jian He

The context here is constraints for partitioning as suggested in
documentation
https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-MAINTENANCE

An example constraint from the documentation:
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );

If logdate is indexed, then this constraint can be manually validated very
quickly using a SELECT that will take advantage of the index
SELECT 1 FROM measurement_y2008m02 WHERE logdate < DATE '2008-02-01' OR
logdate >= DATE '2008-03-01' LIMIT 1

If the constraint is valid the query will return quickly with no rows, if
any rows violate the constraint it will also return very quickly but return
with a single row with column value: 1.

I guess that validating constraints doesn't invoke the query planner, or
otherwise the conversion is too complex for the query planner. The
conversion being:

- from: NOT (logdate >= DATE '2008-02-01' AND logdate < DATE
'2008-03-01')
- to: logdate < DATE '2008-02-01' OR logdate >= DATE '2008-03-01'

Hope that clarifies it.

On Wed, 20 Nov 2024 at 09:45, jian he <jian(dot)universality(at)gmail(dot)com> wrote:

> On Fri, Nov 15, 2024 at 4:38 PM Philip Couling <couling(at)gmail(dot)com> wrote:
> >
> > Is there a solid reason why adding a check constraint does not use
> existing indexes for validation.
> >
>
> can you give an sql example (except not-null)
> where indexes can be used for check constraint validation?
> i am not sure I understand it correctly.
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Achilleas Mantzios - cloud 2024-11-20 12:56:05 Re: Suddenly all queries moved to seq scan
Previous Message Koen De Groote 2024-11-20 11:16:00 Memory settings when running postgres in a docker container