Re: query plan ignoring check constraints

From: "John Hansen" <john(at)geeknet(dot)com(dot)au>
To: "Simon Riggs" <simon(at)2ndquadrant(dot)com>, "Alvaro Herrera" <alvherre(at)surnet(dot)cl>
Cc: "Josh Berkus" <josh(at)agliodbs(dot)com>, <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: query plan ignoring check constraints
Date: 2005-06-20 23:46:50
Message-ID: 5066E5A966339E42AA04BA10BA706AE50A935F@rodrick.geeknet.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Someone Wrote:

> Should not check constraint act as the first filter? The index should
> ideally be scanned only when the check constraint is passed by the
search
> criteria but surprisingly it did not happen. The explain analyze
showed
> cost for index scans of subtables that cannot contain rows matching
the
> search criteria.

Obviously, indexes on columns with a check constraint, should be
qualified with the same check constraint.

test=# CREATE TABLE test (
foo text check(foo IN ('YES','NO'))
);
CREATE TABLE
test=# CREATE INDEX text_foo_idx ON test (foo) WHERE foo IN('YES','NO');
CREATE INDEX
test=# INSERT INTO test VALUES ('YES');
INSERT 280188 1
test=# INSERT INTO test VALUES ('NO');
INSERT 280189 1
test=# INSERT INTO test VALUES ('no');
ERROR: new row for relation "test" violates check constraint
"test_foo_check"
test=# EXPLAIN ANALYZE SELECT * FROM test WHERE foo = 'YES';
QUERY PLAN

------------------------------------------------------------------------
--------------------------------------------
Index Scan using text_foo_idx on test (cost=0.00..5.82 rows=7
width=32) (actual time=0.369..0.376 rows=1 loops=1)
Index Cond: (foo = 'YES'::text)
Total runtime: 0.490 ms
(3 rows)
test=# EXPLAIN ANALYZE SELECT * FROM test WHERE foo = 'no';
QUERY PLAN

------------------------------------------------------------------------
------------------------
Seq Scan on test (cost=0.00..25.38 rows=7 width=32) (actual
time=0.358..0.358 rows=0 loops=1)
Filter: (foo = 'no'::text)
Total runtime: 0.421 ms
(3 rows)
test=#

... John

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2005-06-21 00:37:37 Re: [PATCHES] default database creation with initdb
Previous Message Tom Lane 2005-06-20 23:26:13 Re: make distclean keeps some files