Re: Unnecessary scan from non-overlapping range predicates

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Ajit Awekar <ajitpostgres(at)gmail(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Unnecessary scan from non-overlapping range predicates
Date: 2025-06-25 16:28:02
Message-ID: 1299121.1750868882@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Ajit Awekar <ajitpostgres(at)gmail(dot)com> writes:
> EXPLAIN (costs off)
> select * from products where price < 100 AND price > 300;
> Seq Scan on products
> Filter: ((price < '100'::numeric) AND (price > '300'::numeric))

> Since this condition is false and result will always be empty. Despite
> this, we still perform unnecessary sequential scan over the table.

> Can we detect such contradictory predicates during planning and optimize
> them away using a Result node with One-Time Filter: false. This would avoid
> scanning large tables unnecessarily and improve performance.

This is not done by default because it would be a waste of planner
cycles for well-written queries. However, if you have a lot of
poorly-written queries ...

regression=# create table products (price numeric);
CREATE TABLE
regression=# explain select * from products where price < 100 AND price > 300;
QUERY PLAN
-------------------------------------------------------------------
Seq Scan on products (cost=0.00..30.40 rows=7 width=32)
Filter: ((price < '100'::numeric) AND (price > '300'::numeric))
(2 rows)

regression=# set constraint_exclusion to on;
SET
regression=# explain select * from products where price < 100 AND price > 300;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.00 rows=0 width=0)
One-Time Filter: false
(2 rows)

regards, tom lane

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message vignesh C 2025-06-25 16:49:55 pg_logical_slot_get_changes waits continously for a partial WAL record spanning across 2 pages
Previous Message Tom Lane 2025-06-25 15:58:54 Re: No error checking when reading from file using zstd in pg_dump