pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Do not scan index in right table if condition for left join evaluates to false using columns in left table
23+ messages / 6 participants
[nested] [flat]

* Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 18:30  Илья Жарков <izharkov1243@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Илья Жарков @ 2024-12-07 18:30 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

Hi, could you help to understand why Postgres scans index in right table in
the following case:

CREATE TABLE parent (
>   id integer PRIMARY KEY,
>   dtype text
> );


CREATE TABLE child (
>   id integer PRIMARY KEY
> );


INSERT INTO parent (id, dtype) values (1, 'A');
> INSERT INTO child (id) values (1);


EXPLAIN ANALYZE
> SELECT *
> FROM parent p
> LEFT JOIN child c
>   ON p.id = c.id
>   AND p.dtype = 'B'
> WHERE p.id = 1;


Note that the only record in *parent *table has dtype == 'A', but the join
condition has p.dtype = 'B'.
The query plan still shows Index Only Scan on *child *table with loops=1.

 Nested Loop Left Join  (cost=0.31..16.36 rows=1 width=40) (actual
> time=0.104..0.107 rows=1 loops=1)
>    Join Filter: (p.dtype = 'B'::text)
>    Rows Removed by Join Filter: 1
>    ->  Index Scan using parent_pkey on parent p  (cost=0.15..8.17 rows=1
> width=36) (actual time=0.018..0.019 rows=1 loops=1)
>          Index Cond: (id = 1)
>    ->  Index Only Scan using child_pkey on child c  (cost=0.15..8.17
> rows=1 width=4) (actual time=0.078..0.080 rows=1 loops=1)
>          Index Cond: (id = 1)
>          Heap Fetches: 1


In comparison, if using INNER JOIN, Index Only Scan on *child *table is
never executed.
Tested on PostgreSQL 17.2

^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 21:37  Andres Freund <andres@anarazel.de>
  parent: Илья Жарков <izharkov1243@gmail.com>
  0 siblings, 2 replies; 23+ messages in thread

From: Andres Freund @ 2024-12-07 21:37 UTC (permalink / raw)
  To: Илья Жарков <izharkov1243@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi,

On 2024-12-07 21:30:46 +0300, Илья Жарков wrote:
> Hi, could you help to understand why Postgres scans index in right table in
> the following case:
>
> CREATE TABLE parent (
> >   id integer PRIMARY KEY,
> >   dtype text
> > );
>
>
> CREATE TABLE child (
> >   id integer PRIMARY KEY
> > );
>
>
> INSERT INTO parent (id, dtype) values (1, 'A');
> > INSERT INTO child (id) values (1);
>
>
> EXPLAIN ANALYZE
> > SELECT *
> > FROM parent p
> > LEFT JOIN child c
> >   ON p.id = c.id
> >   AND p.dtype = 'B'
> > WHERE p.id = 1;
>
>
> Note that the only record in *parent *table has dtype == 'A', but the join
> condition has p.dtype = 'B'.
> The query plan still shows Index Only Scan on *child *table with loops=1.

The relevant difference between the inner and left join is that for the inner
join we push down the p.dtype = 'B'::text condition down. However, we do *not*
do so for outer joins.

Outer:
┌───────────────────────────────────────────────────┐
│                    QUERY PLAN                     │
├───────────────────────────────────────────────────┤
│ Nested Loop Left Join                             │
│   Join Filter: (p.dtype = 'B'::text)              │
│   ->  Index Scan using parent_pkey on parent p    │
│         Index Cond: (id = 1)                      │
│   ->  Index Only Scan using child_pkey on child c │
│         Index Cond: (id = 1)                      │
└───────────────────────────────────────────────────┘

Inner:
┌───────────────────────────────────────────────────┐
│                    QUERY PLAN                     │
├───────────────────────────────────────────────────┤
│ Nested Loop                                       │
│   ->  Index Scan using parent_pkey on parent p    │
│         Index Cond: (id = 1)                      │
│         Filter: (dtype = 'B'::text)               │
│   ->  Index Only Scan using child_pkey on child c │
│         Index Cond: (id = 1)                      │
└───────────────────────────────────────────────────┘


We *do* have code that recognizes the case where a clause in a join's ON only
references the nullable side. We however don't have code that recognizes the
same if it's the non-nullable side.

That's somewhat surprising, but it does kinda make sense: A after all, in a
query like yours, you could just have had the p.dtype = 'B' in the WHERE list,
rather than inside the join's ON. The same isn't true for the nullable side of
the join, as a condition for te nullable side in the WHERE clause breaks the
join's "outerness".

I.e. you can write your query as
  SELECT * FROM parent p LEFT JOIN child c ON p.id = c.id WHERE p.id = 1 AND p.dtype = 'B';
in which case you get the expected query plan:
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                         QUERY PLAN                                                          │
├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Nested Loop Left Join  (cost=0.31..16.36 rows=1 width=40) (actual time=0.035..0.036 rows=0 loops=1)                         │
│   ->  Index Scan using parent_pkey on parent p  (cost=0.15..8.17 rows=1 width=36) (actual time=0.034..0.034 rows=0 loops=1) │
│         Index Cond: (id = 1)                                                                                                │
│         Filter: (dtype = 'B'::text)                                                                                         │
│         Rows Removed by Filter: 1                                                                                           │
│   ->  Index Only Scan using child_pkey on child c  (cost=0.15..8.17 rows=1 width=4) (never executed)                        │
│         Index Cond: (id = 1)                                                                                                │
│         Heap Fetches: 0                                                                                                     │
│ Planning Time: 29.912 ms                                                                                                    │
│ Execution Time: 0.095 ms                                                                                                    │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘


ISTM that it shouldn't be expensive to recognize this type of join clause and
pushes them down. While it could be done by the query's author, it seems worth
handling this on our side.  But maybe I'm missing something here?


Greetings,

Andres Freund

PS:

Here's the repro in an easier to copy way:

CREATE TABLE parent (id integer PRIMARY KEY,dtype text not null);
CREATE TABLE child (id integer PRIMARY KEY);
INSERT INTO parent (id, dtype) values (1, 'A');
INSERT INTO child (id) values (1);

EXPLAIN SELECT * FROM parent p LEFT JOIN child c ON p.id = c.id AND p.dtype = 'B' WHERE p.id = 1;
EXPLAIN SELECT * FROM parent p JOIN child c ON p.id = c.id AND p.dtype = 'B' WHERE p.id = 1;





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 22:06  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 23+ messages in thread

From: Tom Lane @ 2024-12-07 22:06 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org

Andres Freund <andres@anarazel.de> writes:
> ISTM that it shouldn't be expensive to recognize this type of join clause and
> pushes them down. While it could be done by the query's author, it seems worth
> handling this on our side.  But maybe I'm missing something here?

No, that condition *can't* be pushed down to the LHS scan, because its
failure should not remove LHS rows from the output; it can only cause
them to have nulls in the RHS columns.

One could imagine that we split up the join filter conditions into
"depends on RHS" and "doesn't depend on RHS" subsets, and make the
nestloop plan node evaluate the latter set only once per LHS row,
and then skip the inner-side scan when that condition fails.
But this would be a bunch of new mechanism that's only useful for
outer joins, only for rather hokey outer join conditions, and only
for nestloop-type joins.  I'm pretty dubious that it's worth the
trouble -- not least because I don't recall anybody complaining
about this before.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 22:21  Andres Freund <andres@anarazel.de>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 23+ messages in thread

From: Andres Freund @ 2024-12-07 22:21 UTC (permalink / raw)
  To: Илья Жарков <izharkov1243@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

On 2024-12-07 16:37:32 -0500, Andres Freund wrote:
> On 2024-12-07 21:30:46 +0300, Илья Жарков wrote:
> > Note that the only record in *parent *table has dtype == 'A', but the join
> > condition has p.dtype = 'B'.
> > The query plan still shows Index Only Scan on *child *table with loops=1.
>
> The relevant difference between the inner and left join is that for the inner
> join we push down the p.dtype = 'B'::text condition down. However, we do *not*
> do so for outer joins.
>
> Outer:
> ┌───────────────────────────────────────────────────┐
> │                    QUERY PLAN                     │
> ├───────────────────────────────────────────────────┤
> │ Nested Loop Left Join                             │
> │   Join Filter: (p.dtype = 'B'::text)              │
> │   ->  Index Scan using parent_pkey on parent p    │
> │         Index Cond: (id = 1)                      │
> │   ->  Index Only Scan using child_pkey on child c │
> │         Index Cond: (id = 1)                      │
> └───────────────────────────────────────────────────┘
>
> Inner:
> ┌───────────────────────────────────────────────────┐
> │                    QUERY PLAN                     │
> ├───────────────────────────────────────────────────┤
> │ Nested Loop                                       │
> │   ->  Index Scan using parent_pkey on parent p    │
> │         Index Cond: (id = 1)                      │
> │         Filter: (dtype = 'B'::text)               │
> │   ->  Index Only Scan using child_pkey on child c │
> │         Index Cond: (id = 1)                      │
> └───────────────────────────────────────────────────┘
>
>
> We *do* have code that recognizes the case where a clause in a join's ON only
> references the nullable side. We however don't have code that recognizes the
> same if it's the non-nullable side.
>
> That's somewhat surprising, but it does kinda make sense: A after all, in a
> query like yours, you could just have had the p.dtype = 'B' in the WHERE list,
> rather than inside the join's ON. The same isn't true for the nullable side of
> the join, as a condition for te nullable side in the WHERE clause breaks the
> join's "outerness".
>
> I.e. you can write your query as
>   SELECT * FROM parent p LEFT JOIN child c ON p.id = c.id WHERE p.id = 1 AND p.dtype = 'B';
> in which case you get the expected query plan:
> ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
> │                                                         QUERY PLAN                                                          │
> ├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
> │ Nested Loop Left Join  (cost=0.31..16.36 rows=1 width=40) (actual time=0.035..0.036 rows=0 loops=1)                         │
> │   ->  Index Scan using parent_pkey on parent p  (cost=0.15..8.17 rows=1 width=36) (actual time=0.034..0.034 rows=0 loops=1) │
> │         Index Cond: (id = 1)                                                                                                │
> │         Filter: (dtype = 'B'::text)                                                                                         │
> │         Rows Removed by Filter: 1                                                                                           │
> │   ->  Index Only Scan using child_pkey on child c  (cost=0.15..8.17 rows=1 width=4) (never executed)                        │
> │         Index Cond: (id = 1)                                                                                                │
> │         Heap Fetches: 0                                                                                                     │
> │ Planning Time: 29.912 ms                                                                                                    │
> │ Execution Time: 0.095 ms                                                                                                    │
> └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Ah, wait - that's not actually equivalent. When p.dtype = 'B' inthe ON clause,
we still produce an output row, but not if in the WHERE clause.

So:

> ISTM that it shouldn't be expensive to recognize this type of join clause and
> pushes them down. While it could be done by the query's author, it seems worth
> handling this on our side.  But maybe I'm missing something here?

yes, I was missing something, it would not be a valid transformation.


I guess it's still somewhat silly that we do an index scan for the inner side,
even though we could know that we'll always fail to the joinqual.  We could
evaluate the qual after fetching the outer row, before fetching the matching
inner row.

It's might not be worth adding code to handle such cases to the the nested
loop code, this is probably not that common a query pattern. If we don't want
to have explict execution time code paths, we could emit a "constant
qualification" Result node above the inner side of a parametrized nested loop?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 23:04  Илья Жарков <izharkov1243@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 23+ messages in thread

From: Илья Жарков @ 2024-12-07 23:04 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers@lists.postgresql.org

I've just realized that I replied not to the whole mailing list. This is a
duplicate of mail sent to Andres.

Thank you for the quick response.

Some background using code and concepts of particular languages and
frameworks:

Exactly such queries are automatically built by Hibernate if using
polymorphic queries with fetching associations of sub-classes using
function treat.
https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#hql-fun...

Reproducer:

@Entity
@Inheritance
@DiscriminatorValue("A")
class Parent {
    @Id
    Integer id;
}

@Entity
@DiscriminatorValue("B")
class ParentB extends Parent {
    @OneToOne(mappedBy = "parent")
    Child child;
}

@Entity
class Child {
    @Id
    Integer id;

    @OneToOne
    @MapsId
    @JoinColumn(name = "id")
    private ParentB parent;
}

List<Parent> resultList = session.createQuery(
        """
        from Parent p
        left join fetch treat(p as ParentB).child
        where p.id = :id
        """, Parent.class)
        .setParameter("id", 1)
        .getResultList();

вс, 8 дек. 2024 г. в 01:21, Andres Freund <andres@anarazel.de>:

> On 2024-12-07 16:37:32 -0500, Andres Freund wrote:
> > On 2024-12-07 21:30:46 +0300, Илья Жарков wrote:
> > > Note that the only record in *parent *table has dtype == 'A', but the
> join
> > > condition has p.dtype = 'B'.
> > > The query plan still shows Index Only Scan on *child *table with
> loops=1.
> >
> > The relevant difference between the inner and left join is that for the
> inner
> > join we push down the p.dtype = 'B'::text condition down. However, we do
> *not*
> > do so for outer joins.
> >
> > Outer:
> > ┌───────────────────────────────────────────────────┐
> > │                    QUERY PLAN                     │
> > ├───────────────────────────────────────────────────┤
> > │ Nested Loop Left Join                             │
> > │   Join Filter: (p.dtype = 'B'::text)              │
> > │   ->  Index Scan using parent_pkey on parent p    │
> > │         Index Cond: (id = 1)                      │
> > │   ->  Index Only Scan using child_pkey on child c │
> > │         Index Cond: (id = 1)                      │
> > └───────────────────────────────────────────────────┘
> >
> > Inner:
> > ┌───────────────────────────────────────────────────┐
> > │                    QUERY PLAN                     │
> > ├───────────────────────────────────────────────────┤
> > │ Nested Loop                                       │
> > │   ->  Index Scan using parent_pkey on parent p    │
> > │         Index Cond: (id = 1)                      │
> > │         Filter: (dtype = 'B'::text)               │
> > │   ->  Index Only Scan using child_pkey on child c │
> > │         Index Cond: (id = 1)                      │
> > └───────────────────────────────────────────────────┘
> >
> >
> > We *do* have code that recognizes the case where a clause in a join's ON
> only
> > references the nullable side. We however don't have code that recognizes
> the
> > same if it's the non-nullable side.
> >
> > That's somewhat surprising, but it does kinda make sense: A after all,
> in a
> > query like yours, you could just have had the p.dtype = 'B' in the WHERE
> list,
> > rather than inside the join's ON. The same isn't true for the nullable
> side of
> > the join, as a condition for te nullable side in the WHERE clause breaks
> the
> > join's "outerness".
> >
> > I.e. you can write your query as
> >   SELECT * FROM parent p LEFT JOIN child c ON p.id = c.id WHERE p.id =
> 1 AND p.dtype = 'B';
> > in which case you get the expected query plan:
> >
> ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
> > │                                                         QUERY PLAN
>                                                       │
> >
> ├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
> > │ Nested Loop Left Join  (cost=0.31..16.36 rows=1 width=40) (actual
> time=0.035..0.036 rows=0 loops=1)                         │
> > │   ->  Index Scan using parent_pkey on parent p  (cost=0.15..8.17
> rows=1 width=36) (actual time=0.034..0.034 rows=0 loops=1) │
> > │         Index Cond: (id = 1)
>                                                       │
> > │         Filter: (dtype = 'B'::text)
>                                                      │
> > │         Rows Removed by Filter: 1
>                                                      │
> > │   ->  Index Only Scan using child_pkey on child c  (cost=0.15..8.17
> rows=1 width=4) (never executed)                        │
> > │         Index Cond: (id = 1)
>                                                       │
> > │         Heap Fetches: 0
>                                                      │
> > │ Planning Time: 29.912 ms
>                                                       │
> > │ Execution Time: 0.095 ms
>                                                       │
> >
> └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
>
> Ah, wait - that's not actually equivalent. When p.dtype = 'B' inthe ON
> clause,
> we still produce an output row, but not if in the WHERE clause.
>
> So:
>
> > ISTM that it shouldn't be expensive to recognize this type of join
> clause and
> > pushes them down. While it could be done by the query's author, it seems
> worth
> > handling this on our side.  But maybe I'm missing something here?
>
> yes, I was missing something, it would not be a valid transformation.
>
>
> I guess it's still somewhat silly that we do an index scan for the inner
> side,
> even though we could know that we'll always fail to the joinqual.  We could
> evaluate the qual after fetching the outer row, before fetching the
> matching
> inner row.
>
> It's might not be worth adding code to handle such cases to the the nested
> loop code, this is probably not that common a query pattern. If we don't
> want
> to have explict execution time code paths, we could emit a "constant
> qualification" Result node above the inner side of a parametrized nested
> loop?
>
> Greetings,
>
> Andres Freund
>


^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 23:07  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 23+ messages in thread

From: Andres Freund @ 2024-12-07 23:07 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi,

On 2024-12-07 17:06:52 -0500, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> > ISTM that it shouldn't be expensive to recognize this type of join clause and
> > pushes them down. While it could be done by the query's author, it seems worth
> > handling this on our side.  But maybe I'm missing something here?
>
> No, that condition *can't* be pushed down to the LHS scan, because its
> failure should not remove LHS rows from the output; it can only cause
> them to have nulls in the RHS columns.

Yea, just sent an email saying so after realizing the same.


> One could imagine that we split up the join filter conditions into
> "depends on RHS" and "doesn't depend on RHS" subsets, and make the
> nestloop plan node evaluate the latter set only once per LHS row,
> and then skip the inner-side scan when that condition fails.
> But this would be a bunch of new mechanism that's only useful for
> outer joins, only for rather hokey outer join conditions, and only
> for nestloop-type joins.  I'm pretty dubious that it's worth the
> trouble -- not least because I don't recall anybody complaining
> about this before.

As I wrote in my other email, I'm also somewhat dubious it's worth having
explicit code for this in nodeNestloop.c.

Not convinced that such queries are that hokey though, it's not that rare a
thing to want to left join to some other table only if the outer side matches
some attribute. We ourselves do have a few cases like that in our queries,
e.g. psql's describeOneTableDetails(), pg_dump's getTables() and several
others.  ...


Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-07 23:13  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 23+ messages in thread

From: Tom Lane @ 2024-12-07 23:13 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org

Andres Freund <andres@anarazel.de> writes:
> On 2024-12-07 17:06:52 -0500, Tom Lane wrote:
>> One could imagine that we split up the join filter conditions into
>> "depends on RHS" and "doesn't depend on RHS" subsets, and make the
>> nestloop plan node evaluate the latter set only once per LHS row,
>> and then skip the inner-side scan when that condition fails.

> As I wrote in my other email, I'm also somewhat dubious it's worth having
> explicit code for this in nodeNestloop.c.

Yeah.  Your idea of pushing the "doesn't depend on RHS" subset into
a one-time Result filter atop the RHS is interesting though.  Then we
don't need any new executor machinery, but we pay for that with a more
complex planner patch.  Not sure how hard that would be.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 02:23  Andrei Lepikhov <lepihov@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 23+ messages in thread

From: Andrei Lepikhov @ 2024-12-08 02:23 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, p.petrov@postgrespro.ru, Andres Freund <andres@anarazel.de>

On 12/8/24 06:13, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
>> On 2024-12-07 17:06:52 -0500, Tom Lane wrote:
>>> One could imagine that we split up the join filter conditions into
>>> "depends on RHS" and "doesn't depend on RHS" subsets, and make the
>>> nestloop plan node evaluate the latter set only once per LHS row,
>>> and then skip the inner-side scan when that condition fails.
> 
>> As I wrote in my other email, I'm also somewhat dubious it's worth having
>> explicit code for this in nodeNestloop.c.
> 
> Yeah.  Your idea of pushing the "doesn't depend on RHS" subset into
> a one-time Result filter atop the RHS is interesting though.  Then we
> don't need any new executor machinery, but we pay for that with a more
> complex planner patch.  Not sure how hard that would be.
Well, I have been working on this topic for some time. Let me share some 
experiences and thoughts. They may be helpful.
I had a user request on this feature, a kind of 'semi-pushdown' clause. 
As production people said, it is quite typical in sales systems to have 
a table of products and additional tables describing product categories. 
Something like that:

CREATE TABLE products (
   id int PRIMARY KEY, payload text DEFAULT 'product',
   price real DEFAULT random(), type text);
CREATE TABLE vehicles (id int PRIMARY KEY, maxspeed int DEFAULT 250);
CREATE TABLE phones (id int PRIMARY KEY, screensize real DEFAULT 6.1);

INSERT INTO products (id,type)
   SELECT x,'v' FROM generate_series(1,5E4) AS x;
INSERT INTO products (id,type)
   SELECT x,'p' FROM generate_series(1+5E4,1E5) AS x;
INSERT INTO vehicles (id) SELECT x FROM generate_series(1,5E4) AS x;
INSERT INTO phones (id) SELECT x FROM generate_series(1+5E4,1E5) AS x;
VACUUM ANALYZE products, vehicles, phones;

They usually need to get top-sales products from different categories 
querying database with something like that:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT * FROM products p
   LEFT JOIN phones ph ON (p.id = ph.id)
   LEFT JOIN vehicles v ON (p.id = v.id)
WHERE p.price > 0.9;

Users just want to optimise such queries and get description of 
different products within a single query. The query they wish to execute 
looks like this:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT * FROM products p
   LEFT JOIN phones ph ON (p.id = ph.id AND p.type = 'p')
   LEFT JOIN vehicles v ON (p.id = v.id AND p.type = 'v')
WHERE p.price > 0.9;

The request was: why not check the RHS-only clause inside a join node 
and save cycles?

To determine how difficult it could be, I wrote a prototype (very raw), 
which shows how it works in action and how many subsystems we have to touch.
Also, I wonder why you think it could work with NestLoop only. I think 
avoiding touching a hash table and an index under MergeJoin can also be 
beneficial.

The patch and reproduction script with resulting EXPLAINs are in the 
attachment. Petr Petrov is doing further work. He may provide additional 
details, if any.


-- 
regards, Andrei Lepikhov

Attachments:

  reproduction.sql (application/sql, 2.1K) download

v2-lazy-join.diff (text/x-patch, 6.8K) download diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 7f4bf6c4db..fd80dc2192 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -66,6 +66,7 @@ ExecNestLoop(PlanState *pstate) TupleTableSlot *outerTupleSlot; TupleTableSlot *innerTupleSlot; ExprState *joinqual; + ExprState *rhs_joinqual; ExprState *otherqual; ExprContext *econtext; ListCell *lc; @@ -79,6 +80,7 @@ ExecNestLoop(PlanState *pstate) nl = (NestLoop *) node->js.ps.plan; joinqual = node->js.joinqual; + rhs_joinqual = node->js.rhs_joinqual; otherqual = node->js.ps.qual; outerPlan = outerPlanState(node); innerPlan = innerPlanState(node); @@ -156,8 +158,15 @@ ExecNestLoop(PlanState *pstate) */ ENL1_printf("getting new inner tuple"); - innerTupleSlot = ExecProcNode(innerPlan); - econtext->ecxt_innertuple = innerTupleSlot; + if (rhs_joinqual && !ExecQual(rhs_joinqual, econtext)) + { + innerTupleSlot = NULL; + } + else + { + innerTupleSlot = ExecProcNode(innerPlan); + econtext->ecxt_innertuple = innerTupleSlot; + } if (TupIsNull(innerTupleSlot)) { @@ -314,6 +323,8 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) nlstate->js.jointype = node->join.jointype; nlstate->js.joinqual = ExecInitQual(node->join.joinqual, (PlanState *) nlstate); + nlstate->js.rhs_joinqual = + ExecInitQual(node->join.rhs_joinqual, (PlanState *) nlstate); /* * detect whether we need only consider the first matching inner tuple diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index f2ed0d81f6..003f949547 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -232,7 +232,7 @@ static RecursiveUnion *make_recursive_union(List *tlist, static BitmapAnd *make_bitmap_and(List *bitmapplans); static BitmapOr *make_bitmap_or(List *bitmapplans); static NestLoop *make_nestloop(List *tlist, - List *joinclauses, List *otherclauses, List *nestParams, + List *joinclauses, List *rhs_joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique); static HashJoin *make_hashjoin(List *tlist, @@ -4352,6 +4352,7 @@ create_nestloop_plan(PlannerInfo *root, Plan *inner_plan; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *rhs_joinclauses = NIL; List *joinclauses; List *otherclauses; Relids outerrelids; @@ -4390,6 +4391,11 @@ create_nestloop_plan(PlannerInfo *root, /* Sort join qual clauses into best execution order */ joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses); + foreach_node(RestrictInfo, rinfo, best_path->jpath.rhs_joinrinfo) + { + rhs_joinclauses = lappend(rhs_joinclauses, rinfo->clause); + } + /* Get the join qual clauses (in plain expression form) */ /* Any pseudoconstant clauses are ignored here */ if (IS_OUTER_JOIN(best_path->jpath.jointype)) @@ -4423,6 +4429,7 @@ create_nestloop_plan(PlannerInfo *root, join_plan = make_nestloop(tlist, joinclauses, + rhs_joinclauses, otherclauses, nestParams, outer_plan, @@ -6021,6 +6028,7 @@ make_bitmap_or(List *bitmapplans) static NestLoop * make_nestloop(List *tlist, List *joinclauses, + List *rhs_joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, @@ -6038,6 +6046,23 @@ make_nestloop(List *tlist, node->join.jointype = jointype; node->join.inner_unique = inner_unique; node->join.joinqual = joinclauses; + + { + ListCell *lc; + + foreach(lc, node->join.joinqual) + { + Node *qual = (Node *) lfirst(lc); + + if (!list_member(rhs_joinclauses, qual)) + continue; + + node->join.joinqual = foreach_delete_current(node->join.joinqual, lc); + } + + } + + node->join.rhs_joinqual = rhs_joinclauses; node->nestParams = nestParams; return node; diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 91c7c4fe2f..0f54450ead 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -2294,6 +2294,14 @@ set_join_references(PlannerInfo *root, Join *join, int rtoffset) rtoffset, NRM_EQUAL, NUM_EXEC_QUAL((Plan *) join)); + join->rhs_joinqual = fix_join_expr(root, + join->rhs_joinqual, + outer_itlist, + inner_itlist, + (Index) 0, + rtoffset, + NRM_EQUAL, + NUM_EXEC_QUAL((Plan *) join)); /* Now do join-type-specific stuff */ if (IsA(join, NestLoop)) diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c index fc97bf6ee2..b7f1dbac23 100644 --- a/src/backend/optimizer/util/pathnode.c +++ b/src/backend/optimizer/util/pathnode.c @@ -2603,6 +2603,13 @@ create_nestloop_path(PlannerInfo *root, pathnode->jpath.innerjoinpath = inner_path; pathnode->jpath.joinrestrictinfo = restrict_clauses; + foreach_node(RestrictInfo, rinfo, restrict_clauses) + { + if (bms_is_subset(rinfo->clause_relids, outer_path->parent->relids)) + pathnode->jpath.rhs_joinrinfo = + lappend(pathnode->jpath.rhs_joinrinfo, rinfo); + } + final_cost_nestloop(root, pathnode, workspace, extra); return pathnode; diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 182a6956bb..14c7610c8c 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -2125,6 +2125,7 @@ typedef struct JoinState bool single_match; /* True if we should skip to next outer tuple * after finding one inner match */ ExprState *joinqual; /* JOIN quals (in addition to ps.qual) */ + ExprState *rhs_joinqual; } JoinState; /* ---------------- diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h index add0f9e45f..c28c23c983 100644 --- a/src/include/nodes/pathnodes.h +++ b/src/include/nodes/pathnodes.h @@ -2085,7 +2085,7 @@ typedef struct JoinPath Path *innerjoinpath; /* path for the inner side of the join */ List *joinrestrictinfo; /* RestrictInfos to apply to join */ - + List *rhs_joinrinfo; /* Outer-side join clauses (filters) */ /* * See the notes for RelOptInfo and ParamPathInfo to understand why * joinrestrictinfo is needed in JoinPath, and can't be merged into the diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 52f29bcdb6..2c90a63e59 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -791,7 +791,8 @@ typedef struct Join Plan plan; JoinType jointype; bool inner_unique; - List *joinqual; /* JOIN quals (in addition to plan.qual) */ + List *joinqual; + List *rhs_joinqual; /* JOIN quals (in addition to plan.qual) */ } Join; /* ----------------
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 02:52  Andres Freund <andres@anarazel.de>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  1 sibling, 2 replies; 23+ messages in thread

From: Andres Freund @ 2024-12-08 02:52 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

Hi,

On 2024-12-08 09:23:42 +0700, Andrei Lepikhov wrote:
> To determine how difficult it could be, I wrote a prototype (very raw),
> which shows how it works in action and how many subsystems we have to touch.

Cool!


> Also, I wonder why you think it could work with NestLoop only.

It doesn't seem to apply to mergejoins. For hashjoins, it doesn't seem worth a
separate evaluation of a expression - something which has noticeable overhead
on its own - given that the cost of a lookup in the hashtable isn't
particularly high. Compare that to the nestloop case where you always need an
indexscan and often will have more complicated subtrees being executed
unnecessarily on the inner side.


> I think avoiding touching a hash table and an index under MergeJoin can also
> be beneficial.

How would you get significant wins for mergejoins? You need to go through both
inner and outer anyway?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 03:11  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 23+ messages in thread

From: Tom Lane @ 2024-12-08 03:11 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Andrei Lepikhov <lepihov@gmail.com>; Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

Andres Freund <andres@anarazel.de> writes:
> On 2024-12-08 09:23:42 +0700, Andrei Lepikhov wrote:
>> I think avoiding touching a hash table and an index under MergeJoin can also
>> be beneficial.

> How would you get significant wins for mergejoins? You need to go through both
> inner and outer anyway?

Yeah, sounds like nonsense to me too.  The reason this can be a win
for nestloop is that we perform a new scan of the inner relation
for each outer row, and if we can skip an inner scan altogether
then we're ahead.  But mergejoin and hashjoin only scan each input
once anyway, so I see no opportunity to save any scan work.

It's barely possible that this is interesting for hash join
because you could save scanning a hash list ... but frankly
I don't believe there could be enough win there to justify
additional mechanism.  Hash join is in a world of hurt already
if there are lots of duplicate hash codes.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 08:44  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 2 replies; 23+ messages in thread

From: Andrei Lepikhov @ 2024-12-08 08:44 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

On 8/12/2024 09:52, Andres Freund wrote:
>> I think avoiding touching a hash table and an index under MergeJoin can also
>> be beneficial.
> 
> How would you get significant wins for mergejoins? You need to go through both
> inner and outer anyway?
In my mind, this trick can be designed for specific cases like sales 
tables, as illustrated before and used by well-rounded developers. I'm 
not sure that such optimisation would be profitable in general. My point 
is that the sales database has lots of categories, and when requesting 
product descriptions, we will not necessarily touch all the categories - 
in that case, the one-sided clause could allow us to avoid scanning some 
tables at all. Am I wrong?
BTW, may it be used in SEMI JOIN cases?

-- 
regards, Andrei Lepikhov






^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 15:24  Илья Жарков <izharkov1243@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  1 sibling, 0 replies; 23+ messages in thread

From: Илья Жарков @ 2024-12-08 15:24 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

Regarding merge joins, I suppose in some edge cases inner set scan might
not even be started.

FROM parent p
LEFT JOIN child c
  ON p.id = c.id
  AND p.dtype = 'B'

        ┌───┐ ┌───┐
parent  │1,A│ │2,A│
        └───┘ └───┘
       ^
        ┌───┐ ┌───┐
child   │ 1 │ │ 2 │
        └───┘ └───┘
       ^

If p.dtype = 'B' was evaluated early, the pointer could move through the
outer set as long as it is evaluated to false.
In the above example, it reaches the end without even accessing the inner
set.

        ┌───┐ ┌───┐
parent  │1,A│ │2,A│
        └───┘ └───┘
                   ^
        ┌───┐ ┌───┐
child   │ 1 │ │ 2 │
        └───┘ └───┘
       ^

In the opposite scenario:

        ┌───┐ ┌───┐
parent  │1,B│ │2,A│
        └───┘ └───┘
       ^
        ┌───┐ ┌───┐
child   │ 1 │ │ 2 │
        └───┘ └───┘
       ^

it would need to start moving the inner pointer at some point.

        ┌───┐ ┌───┐
parent  │1,B│ │2,A│
        └───┘ └───┘
                   ^
        ┌───┐ ┌───┐
child   │ 1 │ │ 2 │
        └───┘ └───┘
             ^

But even in this case, the pointer may not reach the end in the inner set.

Though this highly depends on how merge join is implemented in the Postgres
code. I have to admit that I have a very vague idea on this...

вс, 8 дек. 2024 г. в 11:44, Andrei Lepikhov <lepihov@gmail.com>:

> On 8/12/2024 09:52, Andres Freund wrote:
> >> I think avoiding touching a hash table and an index under MergeJoin can
> also
> >> be beneficial.
> >
> > How would you get significant wins for mergejoins? You need to go
> through both
> > inner and outer anyway?
> In my mind, this trick can be designed for specific cases like sales
> tables, as illustrated before and used by well-rounded developers. I'm
> not sure that such optimisation would be profitable in general. My point
> is that the sales database has lots of categories, and when requesting
> product descriptions, we will not necessarily touch all the categories -
> in that case, the one-sided clause could allow us to avoid scanning some
> tables at all. Am I wrong?
> BTW, may it be used in SEMI JOIN cases?
>
> --
> regards, Andrei Lepikhov
>
>


^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-08 16:37  Andres Freund <andres@anarazel.de>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  1 sibling, 1 reply; 23+ messages in thread

From: Andres Freund @ 2024-12-08 16:37 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

On 2024-12-08 15:44:23 +0700, Andrei Lepikhov wrote:
> On 8/12/2024 09:52, Andres Freund wrote:
> > > I think avoiding touching a hash table and an index under MergeJoin can also
> > > be beneficial.
> > 
> > How would you get significant wins for mergejoins? You need to go through both
> > inner and outer anyway?

> In my mind, this trick can be designed for specific cases like sales tables,
> as illustrated before and used by well-rounded developers.

I'm not saying that the optimization isn't useful, just that i don't think it
makes much sense for mergeoins.

Besides, at least as far as I can see, fundamentally not optimizing mergejoins
in any substantial manner, it also just doesn't seem likely that queries where
this optimization would come up are likely to be planned as mergejoins. If you
have a leftjoin to a category-style table, you're very rarely going to scan
the "main" table with an ordered index scan on the category key, which would
be required for a merge join. And sorting the main table once for each
to-be-joined-category-table isn't a desirable path most of the time either.

I don't know what it means that it's to be "used by well-rounded
developers". We have to write the implementation in way it works regardless of
what kind of developer is using postgres.


> I'm not sure that such optimisation would be profitable in general.

Are you suggesting it would only be enabled by a GUC?


> My point is that the sales database has lots of categories, and when
> requesting product descriptions, we will not necessarily touch all the
> categories - in that case, the one-sided clause could allow us to avoid
> scanning some tables at all. Am I wrong?

No, I don't think you're wrong. I just don't think it's worthwhile for
mergejoins, because I don't see relevant query patterns where it would
help.


> BTW, may it be used in SEMI JOIN cases?

Seems possible.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-09 02:35  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 23+ messages in thread

From: Andrei Lepikhov @ 2024-12-09 02:35 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org; p.petrov@postgrespro.ru

On 8/12/2024 23:37, Andres Freund wrote:
> On 2024-12-08 15:44:23 +0700, Andrei Lepikhov wrote:
>> On 8/12/2024 09:52, Andres Freund wrote:
>>>> I think avoiding touching a hash table and an index under MergeJoin can also
>>>> be beneficial.
>>>
>>> How would you get significant wins for mergejoins? You need to go through both
>>> inner and outer anyway?
> 
>> In my mind, this trick can be designed for specific cases like sales tables,
>> as illustrated before and used by well-rounded developers.
> 
> I'm not saying that the optimization isn't useful, just that i don't think it
> makes much sense for mergeoins.
> 
> Besides, at least as far as I can see, fundamentally not optimizing mergejoins
> in any substantial manner, it also just doesn't seem likely that queries where
> this optimization would come up are likely to be planned as mergejoins. If you
> have a leftjoin to a category-style table, you're very rarely going to scan
> the "main" table with an ordered index scan on the category key, which would
> be required for a merge join. And sorting the main table once for each
> to-be-joined-category-table isn't a desirable path most of the time either.
> 
> I don't know what it means that it's to be "used by well-rounded
> developers". We have to write the implementation in way it works regardless of
> what kind of developer is using postgres.
I got it, thanks. I agree that the profit for MJ & HJ cases looks 
modest. When designing the prototype, I realised that it seemed more 
"symmetrical" and logical to separate such 'one-sided' clauses during 
the planning for all types of join.
But I don't insist on this statement. It would be OK even in the case of 
NestLoop (remember, we should change the NL cost model too).

>> I'm not sure that such optimisation would be profitable in general.
> 
> Are you suggesting it would only be enabled by a GUC?
No, such a feature probably won't generate much overhead; I don't see 
any reason to cover it under a GUC.

-- 
regards, Andrei Lepikhov





^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2024-12-16 09:58  eng eng <pspetrov91@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  1 sibling, 1 reply; 23+ messages in thread

From: eng eng @ 2024-12-16 09:58 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org

пн, 16 дек. 2024 г. в 12:52, Andrei Lepikhov <lepihov@gmail.com>:

> On 12/8/24 06:13, Tom Lane wrote:
> > Andres Freund <andres@anarazel.de> writes:
> >> On 2024-12-07 17:06:52 -0500, Tom Lane wrote:
> >>> One could imagine that we split up the join filter conditions into
> >>> "depends on RHS" and "doesn't depend on RHS" subsets, and make the
> >>> nestloop plan node evaluate the latter set only once per LHS row,
> >>> and then skip the inner-side scan when that condition fails.
> >
> >> As I wrote in my other email, I'm also somewhat dubious it's worth
> having
> >> explicit code for this in nodeNestloop.c.
> >
> > Yeah.  Your idea of pushing the "doesn't depend on RHS" subset into
> > a one-time Result filter atop the RHS is interesting though.  Then we
> > don't need any new executor machinery, but we pay for that with a more
> > complex planner patch.  Not sure how hard that would be.
> Well, I have been working on this topic for some time. Let me share some
> experiences and thoughts. They may be helpful.
> I had a user request on this feature, a kind of 'semi-pushdown' clause.
> As production people said, it is quite typical in sales systems to have
> a table of products and additional tables describing product categories.
> Something like that:
>
> CREATE TABLE products (
>    id int PRIMARY KEY, payload text DEFAULT 'product',
>    price real DEFAULT random(), type text);
> CREATE TABLE vehicles (id int PRIMARY KEY, maxspeed int DEFAULT 250);
> CREATE TABLE phones (id int PRIMARY KEY, screensize real DEFAULT 6.1);
>
> INSERT INTO products (id,type)
>    SELECT x,'v' FROM generate_series(1,5E4) AS x;
> INSERT INTO products (id,type)
>    SELECT x,'p' FROM generate_series(1+5E4,1E5) AS x;
> INSERT INTO vehicles (id) SELECT x FROM generate_series(1,5E4) AS x;
> INSERT INTO phones (id) SELECT x FROM generate_series(1+5E4,1E5) AS x;
> VACUUM ANALYZE products, vehicles, phones;
>
> They usually need to get top-sales products from different categories
> querying database with something like that:
>
> EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
> SELECT * FROM products p
>    LEFT JOIN phones ph ON (p.id = ph.id)
>    LEFT JOIN vehicles v ON (p.id = v.id)
> WHERE p.price > 0.9;
>
> Users just want to optimise such queries and get description of
> different products within a single query. The query they wish to execute
> looks like this:
>
> EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
> SELECT * FROM products p
>    LEFT JOIN phones ph ON (p.id = ph.id AND p.type = 'p')
>    LEFT JOIN vehicles v ON (p.id = v.id AND p.type = 'v')
> WHERE p.price > 0.9;
>
> The request was: why not check the RHS-only clause inside a join node
> and save cycles?
>
> To determine how difficult it could be, I wrote a prototype (very raw),
> which shows how it works in action and how many subsystems we have to
> touch.
> Also, I wonder why you think it could work with NestLoop only. I think
> avoiding touching a hash table and an index under MergeJoin can also be
> beneficial.
>
> The patch and reproduction script with resulting EXPLAINs are in the
> attachment. Petr Petrov is doing further work. He may provide additional
> details, if any.
>
>
> --
> regards, Andrei Lepikhov


Hello!

I would like to describe the main idea:

1) We would like to speed up Nested Loop Left Join execution since getting
the next inner tuple could be expensive.

    Also, not all outer tuples should be matched. For example, we have 200k
rows and inner tuples are extracted only for 100 of them.

    That could allow us to execute Nested Loop Left Join faster.

2) When we analyze RestrictInfo's clauses it is possible to detect whether
it's sufficient to use outer tuple data to calculate them.

    If it is the case, then we save them in rhs_joinrinfo. In the current
patch version that was done in create_nestloop_path().

    Then in make_nestloop() rhs_joinqual clauses were removed from
joinqual.

    Then execute rhs_joinqual in ExecNestLoop() before the next inner tuple
extraction.

    If the result of their evaluation is false then we fill inner tuple's
fields with nulls and return the result without visiting the inner
relation.


3) I also propose to add a new type of filter: Outer Tuple Filter.

    It's a filter which is evaluated after getting the outer tuple but
before extracting the inner tuple.

    Join filter is evaluated after grabbing the inner tuple, that's why I
suggest to differentiate them.

    To calculate unmatched tuples by Outer Tuple Filter an additional
counter was added to Instrumentation struct: int nunmatched.


You can find the execution plan in reproduction.sql

The patch was based on commit 3191eccd8a9bff1715f2e4fab86d2932a556185e

At least, make check-world has passed.

That's my first experience in making patches, so apologize if I
misunderstand or explain something poorly.

Looking forward to your questions and feedback.

---
Best regards,
Peter Petrov

Attachments:

  reproduction.sql (application/sql, 2.4K) download

v3-lazy-join.diff (text/x-patch, 27.4K) download diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index bf322198a20..fd145421a5b 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2407,7 +2407,7 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) + Outer Tuple Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c index a201ed30824..3f6c3dddc41 100644 --- a/src/backend/commands/explain.c +++ b/src/backend/commands/explain.c @@ -2302,6 +2302,12 @@ ExplainNode(PlanState *planstate, List *ancestors, } break; case T_NestLoop: + show_upper_qual(((NestLoop *) plan)->join.rhs_joinqual, + "Outer Tuple Filter", planstate, ancestors, es); + if (((NestLoop *) plan)->join.rhs_joinqual) + show_instrumentation_count("Rows Unmatched by Outer Tuple Filter", 3, + planstate, es); + show_upper_qual(((NestLoop *) plan)->join.joinqual, "Join Filter", planstate, ancestors, es); if (((NestLoop *) plan)->join.joinqual) @@ -3957,6 +3963,8 @@ show_instrumentation_count(const char *qlabel, int which, if (which == 2) nfiltered = planstate->instrument->nfiltered2; + else if (which == 3) + nfiltered = planstate->instrument->nunmatched; else nfiltered = planstate->instrument->nfiltered1; nloops = planstate->instrument->nloops; diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 7f4bf6c4dbb..4a3d7fa0dd4 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -66,6 +66,7 @@ ExecNestLoop(PlanState *pstate) TupleTableSlot *outerTupleSlot; TupleTableSlot *innerTupleSlot; ExprState *joinqual; + ExprState *rhs_joinqual; ExprState *otherqual; ExprContext *econtext; ListCell *lc; @@ -79,6 +80,7 @@ ExecNestLoop(PlanState *pstate) nl = (NestLoop *) node->js.ps.plan; joinqual = node->js.joinqual; + rhs_joinqual = node->js.rhs_joinqual; otherqual = node->js.ps.qual; outerPlan = outerPlanState(node); innerPlan = innerPlanState(node); @@ -152,12 +154,23 @@ ExecNestLoop(PlanState *pstate) } /* - * we have an outerTuple, try to get the next inner tuple. + * we have an outerTuple, try to execute quals related to it. If the + * result is false then we won't get the next inner tuple. Otherwise, + * extract it. */ - ENL1_printf("getting new inner tuple"); + ENL1_printf("executing quals related to outer tuple if any"); - innerTupleSlot = ExecProcNode(innerPlan); - econtext->ecxt_innertuple = innerTupleSlot; + if (rhs_joinqual && !ExecQual(rhs_joinqual, econtext)) + { + InstrCountUnmatched(node, 1); + innerTupleSlot = NULL; + } + else + { + ENL1_printf("getting new inner tuple"); + innerTupleSlot = ExecProcNode(innerPlan); + econtext->ecxt_innertuple = innerTupleSlot; + } if (TupIsNull(innerTupleSlot)) { @@ -314,6 +327,8 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) nlstate->js.jointype = node->join.jointype; nlstate->js.joinqual = ExecInitQual(node->join.joinqual, (PlanState *) nlstate); + nlstate->js.rhs_joinqual = + ExecInitQual(node->join.rhs_joinqual, (PlanState *) nlstate); /* * detect whether we need only consider the first matching inner tuple diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 178c572b021..51a1a29fd2b 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -232,7 +232,7 @@ static RecursiveUnion *make_recursive_union(List *tlist, static BitmapAnd *make_bitmap_and(List *bitmapplans); static BitmapOr *make_bitmap_or(List *bitmapplans); static NestLoop *make_nestloop(List *tlist, - List *joinclauses, List *otherclauses, List *nestParams, + List *joinclauses, List *rhs_joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique); static HashJoin *make_hashjoin(List *tlist, @@ -4352,7 +4352,9 @@ create_nestloop_plan(PlannerInfo *root, Plan *inner_plan; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *rhs_joinclauses = NIL; List *joinclauses; + List *rhs_otherclauses = NIL; List *otherclauses; Relids outerrelids; List *nestParams; @@ -4397,6 +4399,10 @@ create_nestloop_plan(PlannerInfo *root, extract_actual_join_clauses(joinrestrictclauses, best_path->jpath.path.parent->relids, &joinclauses, &otherclauses); + + extract_actual_join_clauses(best_path->jpath.rhs_joinrinfo, + best_path->jpath.path.parent->relids, + &rhs_joinclauses, &rhs_otherclauses); } else { @@ -4423,6 +4429,7 @@ create_nestloop_plan(PlannerInfo *root, join_plan = make_nestloop(tlist, joinclauses, + rhs_joinclauses, otherclauses, nestParams, outer_plan, @@ -6019,6 +6026,7 @@ make_bitmap_or(List *bitmapplans) static NestLoop * make_nestloop(List *tlist, List *joinclauses, + List *rhs_joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, @@ -6036,6 +6044,24 @@ make_nestloop(List *tlist, node->join.jointype = jointype; node->join.inner_unique = inner_unique; node->join.joinqual = joinclauses; + + { + ListCell *lc; + + /* Remove quals from joinqual which belongs to outer relation */ + foreach(lc, node->join.joinqual) + { + Node *qual = (Node *) lfirst(lc); + + if (!list_member(rhs_joinclauses, qual)) + continue; + + node->join.joinqual = foreach_delete_current(node->join.joinqual, lc); + } + + } + + node->join.rhs_joinqual = rhs_joinclauses; node->nestParams = nestParams; return node; diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 6d23df108da..2499dbfa94b 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -2292,6 +2292,16 @@ set_join_references(PlannerInfo *root, Join *join, int rtoffset) NRM_EQUAL, NUM_EXEC_QUAL((Plan *) join)); + /* Process rhs_joinqual as well */ + join->rhs_joinqual = fix_join_expr(root, + join->rhs_joinqual, + outer_itlist, + inner_itlist, + (Index) 0, + rtoffset, + NRM_EQUAL, + NUM_EXEC_QUAL((Plan *) join)); + /* Now do join-type-specific stuff */ if (IsA(join, NestLoop)) { diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c index fc97bf6ee26..bfd5bd3df59 100644 --- a/src/backend/optimizer/util/pathnode.c +++ b/src/backend/optimizer/util/pathnode.c @@ -2603,6 +2603,14 @@ create_nestloop_path(PlannerInfo *root, pathnode->jpath.innerjoinpath = inner_path; pathnode->jpath.joinrestrictinfo = restrict_clauses; + /* If clause_relids belong to outerpath then add it to rhs_joinrinfo list */ + foreach_node(RestrictInfo, rinfo, restrict_clauses) + { + if (bms_is_subset(rinfo->clause_relids, outer_path->parent->relids)) + pathnode->jpath.rhs_joinrinfo = + lappend(pathnode->jpath.rhs_joinrinfo, rinfo); + } + final_cost_nestloop(root, pathnode, workspace, extra); return pathnode; diff --git a/src/include/executor/instrument.h b/src/include/executor/instrument.h index bfd7b6d8445..c79f67f4d08 100644 --- a/src/include/executor/instrument.h +++ b/src/include/executor/instrument.h @@ -88,6 +88,8 @@ typedef struct Instrumentation double nloops; /* # of run cycles for this node */ double nfiltered1; /* # of tuples removed by scanqual or joinqual */ double nfiltered2; /* # of tuples removed by "other" quals */ + double nunmatched; /* # of tuples removed by quals related to + * only outer tuples */ BufferUsage bufusage; /* total buffer usage */ WalUsage walusage; /* total WAL usage */ } Instrumentation; diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 7f71b7625df..815f7b3fd5b 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -1237,6 +1237,11 @@ typedef struct PlanState if (((PlanState *)(node))->instrument) \ ((PlanState *)(node))->instrument->nfiltered2 += (delta); \ } while(0) +#define InstrCountUnmatched(node, delta) \ + do { \ + if (((PlanState *)(node))->instrument) \ + ((PlanState *)(node))->instrument->nunmatched += (delta); \ + } while(0) /* * EPQState is state for executing an EvalPlanQual recheck on a candidate @@ -2124,6 +2129,8 @@ typedef struct JoinState bool single_match; /* True if we should skip to next outer tuple * after finding one inner match */ ExprState *joinqual; /* JOIN quals (in addition to ps.qual) */ + ExprState *rhs_joinqual; /* JOIN quals which can be executed using only + * outer tuple */ } JoinState; /* ---------------- diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h index 0759e00e96d..dd84cd96815 100644 --- a/src/include/nodes/pathnodes.h +++ b/src/include/nodes/pathnodes.h @@ -2087,6 +2087,7 @@ typedef struct JoinPath Path *innerjoinpath; /* path for the inner side of the join */ List *joinrestrictinfo; /* RestrictInfos to apply to join */ + List *rhs_joinrinfo; /* Outer-side join clauses (filters) */ /* * See the notes for RelOptInfo and ParamPathInfo to understand why diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 52f29bcdb69..8f8030803a5 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -792,6 +792,8 @@ typedef struct Join JoinType jointype; bool inner_unique; List *joinqual; /* JOIN quals (in addition to plan.qual) */ + List *rhs_joinqual; /* JOIN quals which can be executed by using + * only outer tuple */ } Join; /* ---------------- diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 1904eb65bb9..b1ca1608666 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2189,7 +2189,7 @@ SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON ------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) + Outer Tuple Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 -> Memoize Cache Key: tenk1.hundred diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 55d44a9bcee..1b7d495abf9 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2430,7 +2430,7 @@ where t4.f1 is null; -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) + Outer Tuple Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) -> Materialize @@ -2458,9 +2458,9 @@ from int4_tbl t1 left join int4_tbl t2 on true -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) + Outer Tuple Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) + Outer Tuple Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 @@ -2523,7 +2523,7 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) + Outer Tuple Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2561,12 +2561,12 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +----------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) + Outer Tuple Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) + Outer Tuple Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 @@ -2590,9 +2590,9 @@ select * from int4_tbl t1 Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) + Outer Tuple Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) + Outer Tuple Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize @@ -2612,11 +2612,11 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) + Outer Tuple Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) + Outer Tuple Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 -> Materialize @@ -2662,7 +2662,7 @@ on t2.q2 = 123; -> Nested Loop Left Join Join Filter: (t2.q1 = t5.q1) -> Nested Loop Left Join - Join Filter: false + Outer Tuple Filter: false -> Seq Scan on int8_tbl t2 Filter: (q2 = 123) -> Result @@ -2676,13 +2676,13 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +----------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) + Outer Tuple Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 -> Seq Scan on int8_tbl t3 Filter: (q1 = t2.q1) @@ -2700,7 +2700,7 @@ select * from int8_tbl t1 -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) + Outer Tuple Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 -> Function Scan on generate_series (7 rows) @@ -2711,13 +2711,13 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +----------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) + Outer Tuple Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 -> Seq Scan on int8_tbl t3 (7 rows) @@ -2728,13 +2728,13 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +---------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) + Outer Tuple Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 -> Memoize Cache Key: t2.two @@ -4196,7 +4196,7 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) + Outer Tuple Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 -> Materialize -> Result @@ -4253,7 +4253,7 @@ where nt3.id = 1 and ss2.b3; -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) + Outer Tuple Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result @@ -4496,7 +4496,7 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) + Outer Tuple Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -4533,7 +4533,7 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) + Outer Tuple Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -4848,7 +4848,7 @@ select t1.* from Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) + Outer Tuple Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 -> Materialize @@ -4909,7 +4909,7 @@ select t1.* from Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) + Outer Tuple Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 -> Materialize @@ -4975,7 +4975,7 @@ select t1.* from Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) + Outer Tuple Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 -> Materialize @@ -5084,7 +5084,7 @@ left join QUERY PLAN -------------------------------- Nested Loop Left Join - Join Filter: false + Outer Tuple Filter: false -> Result -> Result One-Time Filter: false @@ -5100,16 +5100,16 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop -> Nested Loop Left Join - Join Filter: NULL::boolean + Outer Tuple Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) + Outer Tuple Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) -> Materialize @@ -5720,7 +5720,7 @@ from int4_tbl as t1 QUERY PLAN -------------------------------- Nested Loop Left Join - Join Filter: false + Outer Tuple Filter: false -> Seq Scan on int4_tbl t1 -> Result One-Time Filter: false @@ -5742,7 +5742,7 @@ from int4_tbl as t1 QUERY PLAN -------------------------------- Nested Loop Left Join - Join Filter: false + Outer Tuple Filter: false -> Seq Scan on int4_tbl t1 -> Result One-Time Filter: false @@ -5775,7 +5775,7 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) + Outer Tuple Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -5915,7 +5915,7 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) + Outer Tuple Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) -> Seq Scan on a t3 @@ -6122,7 +6122,7 @@ SELECT q2 FROM ------------------------------------------------------ Nested Loop Left Join Output: q2 - Join Filter: NULL::boolean + Outer Tuple Filter: NULL::boolean Filter: (('constant'::text) >= ('constant'::text)) -> Seq Scan on public.int4_tbl Output: int4_tbl.f1 @@ -6144,7 +6144,7 @@ FROM int4_tbl -> Seq Scan on int4_tbl -> Materialize -> Nested Loop Left Join - Join Filter: NULL::boolean + Outer Tuple Filter: NULL::boolean Filter: ((tenk1.unique1 = (42)) OR (tenk1.unique2 = (42))) -> Seq Scan on tenk1 -> Result @@ -7242,7 +7242,7 @@ select * from -------------------------------- Nested Loop Left Join Output: 0, (1), ((1)) - Join Filter: false + Outer Tuple Filter: false -> Result Output: 1 -> Result @@ -7361,7 +7361,7 @@ select * from int8_tbl i8 left join lateral -------------------------------------- Nested Loop Left Join Output: i8.q1, i8.q2, f1, (i8.q2) - Join Filter: false + Outer Tuple Filter: false -> Seq Scan on public.int8_tbl i8 Output: i8.q1, i8.q2 -> Result diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index 965a3a76161..30b169bcf65 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -119,9 +119,9 @@ SELECT * FROM pred_tab t1 QUERY PLAN ------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) + Outer Tuple Filter: (t2.a IS NOT NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) + Outer Tuple Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 -> Materialize -> Seq Scan on pred_tab t2 @@ -135,13 +135,13 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab t3 ON t2.a IS NULL AND t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (false AND (t2.b = 1)) + Outer Tuple Filter: (false AND (t2.b = 1)) -> Seq Scan on pred_tab t2 -> Result One-Time Filter: false @@ -156,9 +156,9 @@ SELECT * FROM pred_tab t1 QUERY PLAN ------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) + Outer Tuple Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) + Outer Tuple Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 -> Materialize -> Seq Scan on pred_tab t2 @@ -191,12 +191,12 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + Outer Tuple Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) + Outer Tuple Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 -> Materialize -> Seq Scan on pred_tab t2 @@ -210,13 +210,13 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab t3 ON (t2.a IS NULL OR t2.c IS NULL) AND t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (false AND (t2.b = 1)) + Outer Tuple Filter: (false AND (t2.b = 1)) -> Seq Scan on pred_tab t2 -> Result One-Time Filter: false @@ -228,12 +228,12 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) + Outer Tuple Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) + Outer Tuple Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 -> Materialize -> Seq Scan on pred_tab t2 @@ -301,13 +301,13 @@ SELECT 1 FROM pred_tab t1 (pred_tab t2 LEFT JOIN pred_tab t3 ON t2.a = t3.a) ON TRUE LEFT JOIN pred_tab t4 ON t1.a IS NULL AND t1.b = 1 RIGHT JOIN pred_tab t5 ON t1.b = t5.b; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Hash Right Join Hash Cond: (t1.b = t5.b) -> Nested Loop Left Join -> Nested Loop Left Join - Join Filter: (false AND (t1.b = 1)) + Outer Tuple Filter: (false AND (t1.b = 1)) -> Seq Scan on pred_tab t1 -> Result One-Time Filter: false
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-05-27 10:11  Andrei Lepikhov <lepihov@gmail.com>
  parent: eng eng <pspetrov91@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-05-27 10:11 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

Hi,

I think we should continue this discussion.

Andreas' idea for a gating Result node seems more interesting than the original
approach and is also looks less invasive.

Here is an updated patch that outlines the solution. It still needs to fix some
issues, benchmarking, and write more tests, but the results so far look
promising. For example, in the reproduction script provided in this thread
earlier, it greatly cuts down the number of inner table scans:

 Nested Loop Left Join (actual rows=10036.00 loops=1)
   ->  Nested Loop Left Join (actual rows=10036.00 loops=1)
         ->  Seq Scan on products p (actual rows=10036.00 loops=1)
               Filter: (price > '0.9'::double precision)
               Rows Removed by Filter: 89964
         ->  Result (actual rows=0.50 loops=10036)
               One-Time Filter: (p.type = 'p'::text)
               ->  Index Scan using phones_pkey on phones ph
			(actual rows=1.00 loops=5026)
                     Index Cond: (id = p.id)
                     Index Searches: 5026
   ->  Result (actual rows=0.50 loops=10036)
         One-Time Filter: (p.type = 'v'::text)
         ->  Index Scan using vehicles_pkey on vehicles v
		(actual rows=1.00 loops=5010)
               Index Cond: (id = p.id)
               Index Searches: 5010

The main question for me now is: is it possible to introduce gating into the
optimisation stage and let the planner pick a 'gated' nest loop based on cost
estimates? To do that, we need to introduce one more node, such as GatingPath,
or change ProjectionPath slightly. As this is a more invasive approach, I prefer
the current one unless evidence emerges that a Path machinery change would be
beneficial for something else.

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments:

0001-Gate-the-NestLoop-inner-side-with-outer-only-join-cl.patch (text/plain, 46.3K) download From 2b7795cf1496f20ba7b2edf5cdd1dc6ba2c69af3 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Tue, 26 May 2026 15:53:04 +0200 Subject: [PATCH] Gate the NestLoop inner side with outer-only join clauses When a NestLoop's joinrestrictinfo holds clauses that reference only the outer relation, evaluating them as a Join Filter is wasteful: the entire inner subplan is re-executed for every outer tuple and every resulting row is discarded whenever the clause is false. The inner scan does no useful work in those iterations and need not be started at all. create_nestloop_path() collects the qualifying RestrictInfos into a new JoinPath field, outer_clauses. Only genuine join quals referencing solely the outer rel are eligible; pseudoconstant, pushed-down and no-relids clauses are skipped, since those are post-join filters with different outer-join semantics. create_nestloop_plan() removes the collected clauses from joinclauses, parameterizes them with replace_nestloop_params(), and wraps the inner plan in a make_gating_result() Result carrying them as resconstantqual. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans, so this is a runtime-only win the planner does not yet credit. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/optimizer/plan/createplan.c | 89 ++++- src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 375 ++++++++++-------- src/test/regress/expected/predicate.out | 113 +++--- src/test/regress/expected/subselect.out | 17 +- 6 files changed, 380 insertions(+), 249 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index e90289e4ab1..7aa86c057d5 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2457,16 +2457,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index de6a183da79..a08660ccd14 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4191,8 +4191,10 @@ create_nestloop_plan(PlannerInfo *root, Plan *outer_plan; Plan *inner_plan; Relids outerrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; List *joinclauses; List *otherclauses; List *nestParams; @@ -4238,8 +4240,29 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they are + * constant for a given outer tuple, so the loop further down can gate + * the inner side with them instead of re-checking them per inner row. + * + * Take only genuine join quals (non-pushed-down); a pushed-down filter + * has different outer-join semantics and must never move into the gate. + * Kept beside extract_actual_join_clauses() so both apply the same + * joinrelids and cannot disagree on what is pushed down. Inner and + * semi joins never arrive here with such a clause: it would be a + * single-rel restriction already pushed down to the outer scan. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (!rinfo->pseudoconstant && + !RINFO_IS_PUSHED_DOWN(rinfo, joinrelids) && + !bms_is_empty(rinfo->clause_relids) && + bms_is_subset(rinfo->clause_relids, outerrelids)) + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4248,6 +4271,15 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Match by Expr pointer (shared, since both + * lists derive from the same RestrictInfos), and do it before + * parameterization while the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4257,6 +4289,61 @@ create_nestloop_plan(PlannerInfo *root, replace_nestloop_params(root, (Node *) otherclauses); } + /* + * Outer-only clauses are constant across the inner scan for a given outer + * tuple, so applying them as a per-rescan gate on the inner side is + * equivalent to the usual per-row join filter: when the gate is false the + * inner side yields no rows, which for an outer join is the same + * null-extended result, but skips the inner scan entirely. + * + * The clauses must be parameterized (outer Vars -> NestLoop params) so the + * gating Result can evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Every Var in the gating qual must belong to this nestloop's outer + * side; otherwise replace_nestloop_params() would strand an outer Var + * on the inner side or mint a param no nestloop supplies. Re-checks + * the clause_relids test from the collection loop above. + */ + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * Unlike the joinclauses above, this runs regardless of param_info: + * the inner side always needs the outer Vars as params. + * + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, so + * re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * resconstantqual takes the clause list directly: ExecInitResult feeds + * it to ExecInitQual, which reads an implicit-AND list. + * + * copy_plan_costsize() carries the child's costs and parallel-safety + * onto the Result unchanged: final_cost_nestloop() does not model the + * skipped inner rescans, so the gate is a runtime-only win the planner + * does not credit (cf. create_gating_plan()). + */ + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 55538c4c41e..71fef89354a 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2250,19 +2250,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 78bf022f7b4..22c58664a73 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -4630,11 +4644,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -4681,18 +4696,19 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result -(9 rows) + One-Time Filter: (0 = nt2.nt1_id) + -> Result +(10 rows) drop function f_immutable_int4(int); -- test inlining when function returns composite @@ -4931,7 +4947,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -4941,9 +4956,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -4968,7 +4985,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -4976,9 +4992,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5277,39 +5295,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -5338,43 +5358,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -5404,46 +5426,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -5537,8 +5561,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -5546,16 +5570,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -6216,7 +6241,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -6226,9 +6250,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -6480,11 +6506,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -7931,14 +7958,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -7959,14 +7987,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -8141,11 +8171,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index a3778c23c34..06013614868 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3575,16 +3575,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL -- 2.54.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-06-30 08:20  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-06-30 08:20 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

On 27/05/2026 12:11, Andrei Lepikhov wrote:
> Here is an updated patch that outlines the solution. It still needs to fix some
> issues, benchmarking, and write more tests, but the results so far look
> promising.

During production-like tests, a clear regression was found. Look:


EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, BUFFERS OFF, SUMMARY OFF)
SELECT count(*) FROM onek t1 LEFT JOIN int4_tbl t2
  ON (t1.unique1 = t2.f1 AND t1.hundred IN (1, 2));

 Aggregate (actual rows=1.00 loops=1)
   ->  Nested Loop Left Join (actual rows=1000.00 loops=1)
         Join Filter: (t1.unique1 = t2.f1)
         Rows Removed by Join Filter: 1000
         ->  Seq Scan on onek t1 (actual rows=1000.00 loops=1)
         ->  Result (actual rows=1.00 loops=1000)
               One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[]))
               ->  Materialize (actual rows=5.00 loops=200)
                     ->  Seq Scan on int4_tbl t2 (actual rows=5.00 loops=200)


Table int4_tbl in this example is rescanned on each rescan of the Materialize
node. The key here is a REWIND flag that NestLoop should set for the inner side
to signal that the subtree is prepared to be rescanned. Without any parameters
inside, materialize node should prepare a tuplestore and skip rescanning of the
underlying subtree. Gating clause adds a parameter to the NestLoop, even if it
doesn't go any deep to the inner subtree.
In this example, 'gating' Result node contains a parameter 't1.hundred' that
signals NestLoop that the inner side may need rebuilding on rescan. So, a gated
NestLoop is a little different animal that lies between parameterised and
non-parameterised NL and deserves to be separated from both somehow.

The solution is quite straightforward: add to the NestLoop struct a flag
'keep_inner_rewind' that is defined as:

keep_inner_rewind =
!bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), outerrelids);

With such a flag, ExecInitNestLoop() can decide whether the inner side itself is
parameterised and set the REWIND flag correctly.

Side story here is a system-dependent output in EXPLAIN. This long-lasting (for
extension tests) problem can be solved with a single function that accumulates
masking tricks across all system-dependent output. Right now, regression tests
have the following:

explain_analyze, explain_analyze_without_memory, explain_mask_costs,
explain_memoize, explain_merge, explain_parallel_append,
explain_parallel_sort_stats, ...

Maybe I missed something.

It is obvious that memory, costs and stats should be filtered out in regression
tests for the sake of stability. So, there is no reason to keep multiple
functions - they may be unified and accessed from everywhere.

See the new version of the patch attached. I treat this version still as a 'draft'.

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments:

v0-0001-Gate-the-NestLoop-inner-side-with-outer-only-join.patch (text/plain, 52.2K) download From 82b07420ccd3beb1e2f437df48853187780f6314 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Tue, 26 May 2026 15:53:04 +0200 Subject: [PATCH v0] Gate the NestLoop inner side with outer-only join clauses When a NestLoop's joinrestrictinfo holds clauses that reference only the outer relation, evaluating them as a Join Filter is wasteful: the entire inner subplan is re-executed for every outer tuple and every resulting row is discarded whenever the clause is false. The inner scan does no useful work in those iterations and need not be started at all. The create_nestloop_plan() removes the collected clauses from joinclauses, parameterizes them with replace_nestloop_params(), and wraps the inner plan in a make_gating_result() Result carrying them as resconstantqual. To not rescan inner subtree in case if no actual parameters exist under the 'gating' clause, the 'keep_inner_rewind' flag in the NestLoop struct is introduced. It is set during the planning and signals the executor init stage that the subtree under the gating clause might be effectively rescanned. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans, so this is a runtime-only win the planner does not yet credit. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 15 +- src/backend/optimizer/plan/createplan.c | 115 ++++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 113 ++--- src/test/regress/expected/subselect.out | 17 +- src/test/regress/sql/join.sql | 27 ++ 9 files changed, 484 insertions(+), 252 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index e90289e4ab1..7aa86c057d5 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2457,16 +2457,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 809311ab513..8b59e185c25 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -290,12 +290,19 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is keep_inner_rewind, which create_nestloop_plan sets when + * the only parameters feed a gating Result that caps the inner subtree and + * is re-checked once per outer tuple. The plan below that gate is then + * parameter-independent and yields the same rows every time, so we keep + * REWIND to let it (typically a Materialize) buffer its output and replay + * it across rescans instead of rebuilding it for every outer tuple that + * passes the gate. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index de6a183da79..1fbd80ec4fe 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4191,8 +4191,11 @@ create_nestloop_plan(PlannerInfo *root, Plan *outer_plan; Plan *inner_plan; Relids outerrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4238,8 +4241,24 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they are + * constant for a given outer tuple, so the loop further down can gate + * the inner side with them instead of re-checking them per inner row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4248,6 +4267,15 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Match by Expr pointer (shared, since both + * lists derive from the same RestrictInfos), and do it before + * parameterization while the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4257,6 +4285,89 @@ create_nestloop_plan(PlannerInfo *root, replace_nestloop_params(root, (Node *) otherclauses); } + /* + * Outer-only clauses are constant across the inner scan for a given outer + * tuple, so applying them as a per-rescan gate on the inner side is + * equivalent to the usual per-row join filter: when the gate is false the + * inner side yields no rows, which for an outer join is the same + * null-extended result, but skips the inner scan entirely. + * + * The clauses must be parameterized (outer Vars -> NestLoop params) so the + * gating Result can evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + bool gate_parallel_safe; + + /* + * Keep the inner rewindable across rescans, but only when this gate is + * the sole source of nestloop parameters. If the inner is itself + * parameterized by the outer (a join key pushed into the inner scan), + * the plan below the gate is parameter-dependent and gains nothing + * from REWIND, so don't request it. See ExecInitNestLoop. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + /* + * Every Var in the gating qual must belong to this nestloop's outer + * side; otherwise replace_nestloop_params() would strand an outer Var + * on the inner side or mint a param no nestloop supplies. Re-checks + * the clause_relids test from the collection loop above. + */ + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * Maintain the parallel-safety flag on the gating Result, mirroring + * create_gating_plan() and change_plan_targetlist(). + */ + gate_parallel_safe = is_parallel_safe(root, (Node *) gating_clauses); + + /* + * Unlike the joinclauses above, this runs regardless of param_info: + * the inner side always needs the outer Vars as params. + * + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a Result, + * merge our parameterized clauses into its resconstantqual (an + * implicit-AND List of expressions) rather than wrapping it. This + * mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + + existing->resconstantqual = (Node *) + list_concat(gating_clauses, + (List *) existing->resconstantqual); + existing->plan.parallel_safe &= gate_parallel_safe; + + /* inner_plan already points at this Result; nothing else to do */ + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + inner_plan->parallel_safe &= gate_parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4330,6 +4441,8 @@ create_nestloop_plan(PlannerInfo *root, best_path->jpath.jointype, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 14a1dfed2b9..5a3fe27ca35 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1008,6 +1008,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 55538c4c41e..71fef89354a 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2250,19 +2250,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 78bf022f7b4..640ac750d51 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -4630,11 +4644,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -4681,17 +4696,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -4931,7 +4946,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -4941,9 +4955,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -4968,7 +4984,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -4976,9 +4991,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5277,39 +5294,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -5338,43 +5357,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -5404,46 +5425,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -5537,8 +5560,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -5546,16 +5569,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -6216,7 +6240,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -6226,9 +6249,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -6480,11 +6505,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -7931,14 +7957,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -7959,14 +7986,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -8141,11 +8170,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but @@ -10143,3 +10173,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index a3778c23c34..06013614868 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3575,16 +3575,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index fae19113cef..0e58c2f0c48 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -3891,3 +3891,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.54.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-07-03 10:53  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-07-03 10:53 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

On 30/06/2026 10:20, Andrei Lepikhov wrote:
> See the new version of the patch attached. I treat this version still as a 'draft'.
This is the updated version of the feature.

- Merged into the existing Result logic. Added an Assert to check that
resconstantqual is a List or NULL, which documents the implicit AND contract at
the point where it is assumed. The combined qual list now uses
order_qual_clauses(), so clauses are executed in cost order.

- Parallel-safety handling reworked. That walk was redundant: the gating clauses
are a subset of the join's restrictlist, whose safety build_join_rel() already
folded into the join path's parallel_safe. Both branches now simply assign
best_path->jpath.path.parallel_safe, matching create_gating_plan()'s pattern

- Fixed compatibility with pg_plan_advice. I still do not understand why a
built-in extension should limit the possible plan choices, since this adds extra
development work and pushes most planner extension modules out of the market.
For now, I have only made a small correction until we discuss this further.

- Also, I passed all the updated tests. We have an impressive diff that shows
the benefits of cost-based decision-making. But this implementation is a clear
win while still leaving room for an optimiser-side version in the future. Since
the path-based implementation is more invasive, it makes sense to consider it
only if another use case for the GatingPath node appears. Seems nice enough to
be added to the next commitfest.

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments: download all (2 files, .tar.gz)

v1-0001-Gate-the-NestLoop-inner-side-with-outer-only-join.patch (text/plain, 50.9K) download From 9b82f32cc8797390d660f39c63dadfebebbcd04a Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Tue, 26 May 2026 15:53:04 +0200 Subject: [PATCH v1 1/2] Gate the NestLoop inner side with outer-only join clauses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some cases, a LEFT JOIN’s NestLoop might have a clause that depends only on the outer side of the join. In such a case, if the outer tuple evaluates this clause as false, the result of the inner side scan operation will not impact the join’s output: inner side will always be replaced with NULL values. Treat such an outer-side clause as a ‘gating’ clause and push it into the inner side as a Result node. It will reduce the number of rescan operations to a bare minimum when the the gating clause evaluates to a true. This operation effectively forces parameterisation of the NestLoop JOIN, even if it was originally plain. To identify such cases, the NestLoop struct was supplemented with a flag that allows the executor to distinguish a ‘gated’ join from the parameterised NestLoop and to set the REWIND flag correctly. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 12 +- src/backend/optimizer/plan/createplan.c | 93 +++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 113 ++--- src/test/regress/expected/subselect.out | 17 +- src/test/regress/sql/join.sql | 27 ++ 9 files changed, 459 insertions(+), 252 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index e90289e4ab1..7aa86c057d5 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2457,16 +2457,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 809311ab513..b49aa8190ea 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -290,12 +290,16 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is a 'gated' nested loop join, where the only parameters + * feed a gating Result that caps the inner subtree and is re-checked once + * per outer tuple. The plan below that gate is parameter-independent, so + * we keep the REWIND flag. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index de6a183da79..3d09c32d084 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4191,8 +4191,11 @@ create_nestloop_plan(PlannerInfo *root, Plan *outer_plan; Plan *inner_plan; Relids outerrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4238,8 +4241,24 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they are + * constant for a given outer tuple, so the loop further down can gate + * the inner side with them instead of re-checking them per inner row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4248,6 +4267,14 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Do this before parameterization, while + * the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4257,6 +4284,68 @@ create_nestloop_plan(PlannerInfo *root, replace_nestloop_params(root, (Node *) otherclauses); } + /* + * The gating clauses must be parameterized so the gating Result can + * evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Keep the inner side rewindable across rescans, but only when this + * gate is the sole source of nestloop parameters. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a Result, + * merge our parameterized clauses into its resconstantqual. This + * mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + List *clauses = (List *) existing->resconstantqual; + + Assert(clauses == NULL || IsA(clauses, List)); + + clauses = list_concat(gating_clauses, clauses); + clauses = order_qual_clauses(root, clauses); + existing->resconstantqual = (Node *) clauses; + + /* Gating quals could be unsafe, so use the Path's safety flag */ + existing->plan.parallel_safe = best_path->jpath.path.parallel_safe; + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + + /* Gating quals could be unsafe, so use the Path's safety flag */ + inner_plan->parallel_safe = best_path->jpath.path.parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4330,6 +4419,8 @@ create_nestloop_plan(PlannerInfo *root, best_path->jpath.jointype, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 14a1dfed2b9..5a3fe27ca35 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1008,6 +1008,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 55538c4c41e..71fef89354a 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2250,19 +2250,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 78bf022f7b4..640ac750d51 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -4630,11 +4644,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -4681,17 +4696,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -4931,7 +4946,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -4941,9 +4955,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -4968,7 +4984,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -4976,9 +4991,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5277,39 +5294,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -5338,43 +5357,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -5404,46 +5425,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -5537,8 +5560,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -5546,16 +5569,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -6216,7 +6240,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -6226,9 +6249,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -6480,11 +6505,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -7931,14 +7957,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -7959,14 +7986,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -8141,11 +8170,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but @@ -10143,3 +10173,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index a3778c23c34..06013614868 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3575,16 +3575,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index fae19113cef..0e58c2f0c48 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -3891,3 +3891,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.54.0
v1-0002-pg_plan_advice-look-through-gating-Results-on-the.patch (text/plain, 1.8K) download From bfe745ef598bb4b0811b9f02498a80575e959089 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 3 Jul 2026 11:58:04 +0200 Subject: [PATCH v1 2/2] pg_plan_advice: look through gating Results on the NestLoop inner side The preceding commit introduced a new plan shape: the inner side of a NestLoop may now be capped by a gating Result that evaluates outer-only join clauses as a one-time filter, sitting above any Material or Memoize node. pgpa_decompose_join() was unaware of this. Teach the NestLoop case to descend through a gating Result before the strategy checks. This restores the node ordering the rest of the function expects and classifies the strategy as MATERIALIZE/MEMOIZE again. A childless Result is deliberately not descended: it is itself the scan and carries its own RTIs. --- contrib/pg_plan_advice/pgpa_join.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contrib/pg_plan_advice/pgpa_join.c b/contrib/pg_plan_advice/pgpa_join.c index 067321081e7..8c1c8c355c5 100644 --- a/contrib/pg_plan_advice/pgpa_join.c +++ b/contrib/pg_plan_advice/pgpa_join.c @@ -389,6 +389,16 @@ pgpa_decompose_join(pgpa_plan_walker_context *walker, Plan *plan, case T_NestLoop: + /* + * create_nestloop_plan() may have capped the inner side with a + * gating Result that evaluates outer-only join clauses as a + * one-time filter. It sits above any Material or Memoize node, + * so look through it before determining the join strategy. + */ + if (elidedinner == NULL && is_result_node_with_child(innerplan) && + ((Result *) innerplan)->resconstantqual != NULL) + elidedinner = pgpa_descend_node(pstmt, &innerplan); + /* * The planner may have chosen to place a Material or Memoize node * on the inner side of the NestLoop; if this is present, we -- 2.54.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-07-28 08:13  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-07-28 08:13 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

Here is the rebased patch set, requested by the commitfest platform.

The following development directions:

1. As this 'lazy join' machinery has a massive footprint in regression tests, I
think it makes sense to investigate a cost-based way.
It isn't strictly necessary, because a gated NestLoop doesn't add any
perceptible overhead, and, for the sake of simplicity and safety, this
optimisation might remain opportunistic. Also, a cost-based approach leads to
more mistakenly picked NestLoop paths in the case of wrong estimates, as well as
more intensive usage when gated NestLoop paths are more efficient than HashJoin
or MergeJoin paths (I have such cases in the pocket already).

2. Platform-independent EXPLAIN output.
The first patch adds the platform_independent_explain routine that hides
unstable memory size. It is a little annoying considering that different
regression tests solve it separately. Considering that extensions also need such
a routine, it might be useful to invent a single routine that post-processes
EXPLAIN (ANALYZE, BUFFERS OFF, TIMING OFF, SUMMARY OFF) and removes any
platform-dependent information at each regression test that needs that. This
topic might be discussed and done in a separate thread.

3. pg_plan_advice patch.
It seems annoying that something outside the planner core performs a formal plan
check, not a semantic one (if possible), adds extra work, and almost undermines
the extensible approach for new planner features. But we still need to identify
the correct way to extend this machinery - now it is quite a formal fix.

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments: download all (2 files, .tar.gz)

0001-Gate-the-NestLoop-inner-side-with-outer-only-join-cl.patch (text/plain, 50.9K) download From 342ac4becff58d5351adc85ead686d0ccb43a201 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <andrei.lepikhov@pgedge.com> Date: Wed, 15 Jul 2026 12:06:36 +1000 Subject: [PATCH 1/3] Gate the NestLoop inner side with outer-only join clauses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some cases, a LEFT JOIN’s NestLoop might have a clause that depends only on the outer side of the join. In such a case, if the outer tuple evaluates this clause as false, the result of the inner side scan operation will not impact the join’s output: inner side will always be replaced with NULL values. Treat such an outer-side clause as a ‘gating’ clause and push it into the inner side as a Result node. It will reduce the number of rescan operations to a bare minimum when the the gating clause evaluates to a true. This operation effectively forces parameterisation of the NestLoop JOIN, even if it was originally plain. To identify such cases, the NestLoop struct was supplemented with a flag that allows the executor to distinguish a ‘gated’ join from the parameterised NestLoop and to set the REWIND flag correctly. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 12 +- src/backend/optimizer/plan/createplan.c | 93 +++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 113 ++--- src/test/regress/expected/subselect.out | 17 +- src/test/regress/sql/join.sql | 27 ++ 9 files changed, 459 insertions(+), 252 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index d19121b05da..60b4efeb486 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2532,16 +2532,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 809311ab513..b49aa8190ea 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -290,12 +290,16 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is a 'gated' nested loop join, where the only parameters + * feed a gating Result that caps the inner subtree and is re-checked once + * per outer tuple. The plan below that gate is parameter-independent, so + * we keep the REWIND flag. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 2c696ea0268..2e4e7fe2459 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4198,8 +4198,11 @@ create_nestloop_plan(PlannerInfo *root, Plan *inner_plan; Relids outerrelids; Relids ojrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4245,8 +4248,24 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they are + * constant for a given outer tuple, so the loop further down can gate + * the inner side with them instead of re-checking them per inner row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4255,6 +4274,14 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Do this before parameterization, while + * the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4269,6 +4296,68 @@ create_nestloop_plan(PlannerInfo *root, bms_union(best_path->jpath.outerjoinpath->parent->relids, best_path->jpath.innerjoinpath->parent->relids)); + /* + * The gating clauses must be parameterized so the gating Result can + * evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Keep the inner side rewindable across rescans, but only when this + * gate is the sole source of nestloop parameters. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a Result, + * merge our parameterized clauses into its resconstantqual. This + * mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + List *clauses = (List *) existing->resconstantqual; + + Assert(clauses == NULL || IsA(clauses, List)); + + clauses = list_concat(gating_clauses, clauses); + clauses = order_qual_clauses(root, clauses); + existing->resconstantqual = (Node *) clauses; + + /* Gating quals could be unsafe, so use the Path's safety flag */ + existing->plan.parallel_safe = best_path->jpath.path.parallel_safe; + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + + /* Gating quals could be unsafe, so use the Path's safety flag */ + inner_plan->parallel_safe = best_path->jpath.path.parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4343,6 +4432,8 @@ create_nestloop_plan(PlannerInfo *root, ojrelids, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index b880ce0f4be..599e16907d7 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1010,6 +1010,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 7b2640f0e04..f9db7416306 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2260,19 +2260,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 19e2cca548b..19ddc56997b 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -4657,11 +4671,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -4708,17 +4723,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -4958,7 +4973,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -4968,9 +4982,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -4995,7 +5011,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -5003,9 +5018,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5304,39 +5321,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -5365,43 +5384,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -5431,46 +5452,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -5564,8 +5587,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -5573,16 +5596,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -6243,7 +6267,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -6253,9 +6276,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -6507,11 +6532,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -7992,14 +8018,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -8020,14 +8047,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -8202,11 +8231,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but @@ -10204,3 +10234,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index e7ff7191082..07d7dfa1891 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3789,16 +3789,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 85aed7bf704..28a9399b1bd 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -3920,3 +3920,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.55.0
0002-pg_plan_advice-look-through-gating-Results-on-the-Ne.patch (text/plain, 1.8K) download From ba353da0a279783b1adf8661040513e32355ae2b Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 3 Jul 2026 11:58:04 +0200 Subject: [PATCH 2/3] pg_plan_advice: look through gating Results on the NestLoop inner side The preceding commit introduced a new plan shape: the inner side of a NestLoop may now be capped by a gating Result that evaluates outer-only join clauses as a one-time filter, sitting above any Material or Memoize node. pgpa_decompose_join() was unaware of this. Teach the NestLoop case to descend through a gating Result before the strategy checks. This restores the node ordering the rest of the function expects and classifies the strategy as MATERIALIZE/MEMOIZE again. A childless Result is deliberately not descended: it is itself the scan and carries its own RTIs. --- contrib/pg_plan_advice/pgpa_join.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contrib/pg_plan_advice/pgpa_join.c b/contrib/pg_plan_advice/pgpa_join.c index e69c25551a0..f3f2ad62f7c 100644 --- a/contrib/pg_plan_advice/pgpa_join.c +++ b/contrib/pg_plan_advice/pgpa_join.c @@ -388,6 +388,16 @@ pgpa_decompose_join(pgpa_plan_walker_context *walker, Plan *plan, case T_NestLoop: + /* + * create_nestloop_plan() may have capped the inner side with a + * gating Result that evaluates outer-only join clauses as a + * one-time filter. It sits above any Material or Memoize node, + * so look through it before determining the join strategy. + */ + if (elidedinner == NULL && is_result_node_with_child(innerplan) && + ((Result *) innerplan)->resconstantqual != NULL) + elidedinner = pgpa_descend_node(pstmt, &innerplan); + /* * The planner may have chosen to place a Material or Memoize node * on the inner side of the NestLoop; if this is present, we -- 2.55.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-09-01 09:16  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-09-01 09:16 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

On 28/07/2026 10:13, Andrei Lepikhov wrote:

Just a rebase onto current master

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments: download all (2 files, .tar.gz)

v2-0001-Gate-the-NestLoop-inner-side-with-outer-only-join.patch (text/plain, 50.9K) download From d586afe7821fd2b676d4553bf582d849fa8f3583 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <andrei.lepikhov@pgedge.com> Date: Wed, 15 Jul 2026 12:06:36 +1000 Subject: [PATCH v2 1/2] Gate the NestLoop inner side with outer-only join clauses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some cases, a LEFT JOIN’s NestLoop might have a clause that depends only on the outer side of the join. In such a case, if the outer tuple evaluates this clause as false, the result of the inner side scan operation will not impact the join’s output: inner side will always be replaced with NULL values. Treat such an outer-side clause as a ‘gating’ clause and push it into the inner side as a Result node. It will reduce the number of rescan operations to a bare minimum when the the gating clause evaluates to a true. This operation effectively forces parameterisation of the NestLoop JOIN, even if it was originally plain. To identify such cases, the NestLoop struct was supplemented with a flag that allows the executor to distinguish a ‘gated’ join from the parameterised NestLoop and to set the REWIND flag correctly. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 12 +- src/backend/optimizer/plan/createplan.c | 93 +++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 113 ++--- src/test/regress/expected/subselect.out | 17 +- src/test/regress/sql/join.sql | 27 ++ 9 files changed, 459 insertions(+), 252 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index 517d15cf1fa..ac6d8d851a1 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2532,16 +2532,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index da48c9b204b..7da6eb49fc1 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -263,12 +263,16 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is a 'gated' nested loop join, where the only parameters + * feed a gating Result that caps the inner subtree and is re-checked once + * per outer tuple. The plan below that gate is parameter-independent, so + * we keep the REWIND flag. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 02a888c5996..50e7e71370b 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4200,8 +4200,11 @@ create_nestloop_plan(PlannerInfo *root, Plan *inner_plan; Relids outerrelids; Relids ojrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4247,8 +4250,24 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they are + * constant for a given outer tuple, so the loop further down can gate + * the inner side with them instead of re-checking them per inner row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4257,6 +4276,14 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Do this before parameterization, while + * the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4271,6 +4298,68 @@ create_nestloop_plan(PlannerInfo *root, bms_union(best_path->jpath.outerjoinpath->parent->relids, best_path->jpath.innerjoinpath->parent->relids)); + /* + * The gating clauses must be parameterized so the gating Result can + * evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Keep the inner side rewindable across rescans, but only when this + * gate is the sole source of nestloop parameters. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a Result, + * merge our parameterized clauses into its resconstantqual. This + * mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + List *clauses = (List *) existing->resconstantqual; + + Assert(clauses == NULL || IsA(clauses, List)); + + clauses = list_concat(gating_clauses, clauses); + clauses = order_qual_clauses(root, clauses); + existing->resconstantqual = (Node *) clauses; + + /* Gating quals could be unsafe, so use the Path's safety flag */ + existing->plan.parallel_safe = best_path->jpath.path.parallel_safe; + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + + /* Gating quals could be unsafe, so use the Path's safety flag */ + inner_plan->parallel_safe = best_path->jpath.path.parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4345,6 +4434,8 @@ create_nestloop_plan(PlannerInfo *root, ojrelids, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 2fe6b61afaf..dce46966685 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1010,6 +1010,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 7b2640f0e04..f9db7416306 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2260,19 +2260,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..43e73268328 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -5404,11 +5418,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -5455,17 +5470,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -5705,7 +5720,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -5715,9 +5729,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5742,7 +5758,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -5750,9 +5765,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -6051,39 +6068,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -6112,43 +6131,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -6178,46 +6199,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -6311,8 +6334,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -6320,16 +6343,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -6990,7 +7014,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -7000,9 +7023,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -7287,11 +7312,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -8871,14 +8897,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -8899,14 +8926,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -9081,11 +9110,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check that quals of a jointree node that becomes empty when the self-join -- is removed are not lost, and that they don't migrate above an outer join @@ -11108,3 +11138,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index ce0ff764417..20ffdf01982 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3789,16 +3789,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..2194d5df64e 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -4271,3 +4271,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.55.0
v2-0002-pg_plan_advice-look-through-gating-Results-on-the.patch (text/plain, 1.8K) download From e0d0dc940ad78d3a92810cbaa83abacd9bc3bb50 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 3 Jul 2026 11:58:04 +0200 Subject: [PATCH v2 2/2] pg_plan_advice: look through gating Results on the NestLoop inner side The preceding commit introduced a new plan shape: the inner side of a NestLoop may now be capped by a gating Result that evaluates outer-only join clauses as a one-time filter, sitting above any Material or Memoize node. pgpa_decompose_join() was unaware of this. Teach the NestLoop case to descend through a gating Result before the strategy checks. This restores the node ordering the rest of the function expects and classifies the strategy as MATERIALIZE/MEMOIZE again. A childless Result is deliberately not descended: it is itself the scan and carries its own RTIs. --- contrib/pg_plan_advice/pgpa_join.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contrib/pg_plan_advice/pgpa_join.c b/contrib/pg_plan_advice/pgpa_join.c index e69c25551a0..f3f2ad62f7c 100644 --- a/contrib/pg_plan_advice/pgpa_join.c +++ b/contrib/pg_plan_advice/pgpa_join.c @@ -388,6 +388,16 @@ pgpa_decompose_join(pgpa_plan_walker_context *walker, Plan *plan, case T_NestLoop: + /* + * create_nestloop_plan() may have capped the inner side with a + * gating Result that evaluates outer-only join clauses as a + * one-time filter. It sits above any Material or Memoize node, + * so look through it before determining the join strategy. + */ + if (elidedinner == NULL && is_result_node_with_child(innerplan) && + ((Result *) innerplan)->resconstantqual != NULL) + elidedinner = pgpa_descend_node(pstmt, &innerplan); + /* * The planner may have chosen to place a Material or Memoize node * on the inner side of the NestLoop; if this is present, we -- 2.55.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-09-12 12:02  Andrei Lepikhov <lepihov@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Andrei Lepikhov @ 2026-09-12 12:02 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

On 01/09/2026 11:16, Andrei Lepikhov wrote:
> On 28/07/2026 10:13, Andrei Lepikhov wrote:
> 
> Just a rebase onto current master
> 

Another rebase to follow the master branch.

I have also looked at the downside of the opportunistic approach this feature
takes. The pros are obvious: zero planning overhead, no search-space blowup, and
simple code. But what does the worst case look like?

By gating the inner side, we add one more node (Result) and force the gating
qual to be evaluated once per outer row. The vanilla NestLoop sometimes does not
do that: when the inner side returns no tuple, a LEFT join goes straight to the
null-fill path and ExecQual(joinqual) is never reached at all. So the gated plan
pays for the clause on every outer row. I think a parameterised index scan that
finds no match is the common case for this behaviour.

The worst query therefore looks like this:

CREATE TABLE o (a int, t text);
INSERT INTO o SELECT g, 'row'||g FROM generate_series(1,1000000) g;
CREATE TABLE i (a int, b int);
ANALYZE o, i;

SET enable_hashjoin = off;
SET enable_mergejoin = off;
SET max_parallel_workers_per_gather = 0;
\timing on

SELECT count(*) FROM ( SELECT * FROM o
  LEFT JOIN i ON (md5(md5(md5(md5(o.t)))) <> 'z')) s;

Making the gate progressively more expensive shows what is going on.
On the current master, I see ~470ms, with the gating clause ~1500ms. This effect
is linear but isn't limited; it depends on the number of evaluations and the
outer size.

The basic case, when each row passes the gate (and correspondent join clause)
doesn't show any degradation, there are no significant difference between gated
and no-gated approach. To reproduce just add one row into the inner table and
re-execute the query above:

INSERT INTO i (a,b) VALUES (1, 1);

My conclusion is this. A gated NestLoop usually behaves like a normal NestLoop
adding benefit of reduced inner scans or nothing. In the degenerate case where
the inner side returns nothing, it adds an overhead proportional to the outer
size times the cost of the gating clause, with no ceiling. Separately, the
Result projection adds a per-joined- tuple cost that grows with the width of the
inner targetlist.

I do not see this as a fundamental problem, except for SubPlan cases - but
SubPlan is a different animal, and every new correlated pull-up technique
attracts complaints of exactly this shape.

So the real question is whether the cost model can account for these two terms
well enough to choose between a gated and a non-gated NestLoop, assuming we turn
this into a cost-based optimisation.

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments: download all (2 files, .tar.gz)

v3-0001-Gate-the-NestLoop-inner-side-with-outer-only-join.patch (text/plain, 50.8K) download From a7954088609ce524998d6fc51a3b1f902c7750c1 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 11 Sep 2026 16:39:23 +0200 Subject: [PATCH v3 1/2] Gate the NestLoop inner side with outer-only join clauses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some cases, a LEFT JOIN’s NestLoop might have a clause that depends only on the outer side of the join. In such a case, if the outer tuple evaluates this clause as false, the result of the inner side scan operation will not impact the join’s output: inner side will always be replaced with NULL values. Treat such an outer-side clause as a ‘gating’ clause and push it into the inner side as a Result node. It will reduce the number of rescan operations to a bare minimum when the the gating clause evaluates to a true. This operation effectively forces parameterisation of the NestLoop JOIN, even if it was originally plain. To identify such cases, the NestLoop struct was supplemented with a flag that allows the executor to distinguish a ‘gated’ join from the parameterised NestLoop and to set the REWIND flag correctly. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 12 +- src/backend/optimizer/plan/createplan.c | 94 +++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 113 ++--- src/test/regress/expected/subselect.out | 17 +- src/test/regress/sql/join.sql | 27 ++ 9 files changed, 460 insertions(+), 252 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index a6295674daf..8421c37f8de 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2532,16 +2532,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index da48c9b204b..7da6eb49fc1 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -263,12 +263,16 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is a 'gated' nested loop join, where the only parameters + * feed a gating Result that caps the inner subtree and is re-checked once + * per outer tuple. The plan below that gate is parameter-independent, so + * we keep the REWIND flag. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 430f6557f1f..958fca137f0 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4201,8 +4201,11 @@ create_nestloop_plan(PlannerInfo *root, Relids outerrelids; Relids req_outer; Relids ojrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4257,8 +4260,25 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they + * are constant for a given outer tuple, so the loop further down can + * gate the inner side with them instead of re-checking them per inner + * row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4267,6 +4287,14 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Do this before parameterization, while + * the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4302,6 +4330,68 @@ create_nestloop_plan(PlannerInfo *root, } } + /* + * The gating clauses must be parameterized so the gating Result can + * evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Keep the inner side rewindable across rescans, but only when this + * gate is the sole source of nestloop parameters. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a + * Result, merge our parameterized clauses into its resconstantqual. + * This mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + List *clauses = (List *) existing->resconstantqual; + + Assert(clauses == NULL || IsA(clauses, List)); + + clauses = list_concat(gating_clauses, clauses); + clauses = order_qual_clauses(root, clauses); + existing->resconstantqual = (Node *) clauses; + + /* Gating quals could be unsafe, so use the Path's safety flag */ + existing->plan.parallel_safe = best_path->jpath.path.parallel_safe; + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + + /* Gating quals could be unsafe, so use the Path's safety flag */ + inner_plan->parallel_safe = best_path->jpath.path.parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4374,6 +4464,8 @@ create_nestloop_plan(PlannerInfo *root, ojrelids, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 2fe6b61afaf..dce46966685 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1010,6 +1010,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 7b2640f0e04..f9db7416306 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2260,19 +2260,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 051c3539930..74fd18800ff 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -5465,11 +5479,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -5516,17 +5531,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -5766,7 +5781,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -5776,9 +5790,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5803,7 +5819,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -5811,9 +5826,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -6112,39 +6129,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -6173,43 +6192,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -6239,46 +6260,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -6372,8 +6395,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -6381,16 +6404,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -7229,7 +7253,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -7239,9 +7262,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -7526,11 +7551,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -9110,14 +9136,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -9138,14 +9165,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -9320,11 +9349,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check that quals of a jointree node that becomes empty when the self-join -- is removed are not lost, and that they don't migrate above an outer join @@ -11347,3 +11377,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..357c1ad1e08 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -244,26 +250,27 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON EXISTS (SELECT 1 FROM pred_tab t3, pred_tab t4, pred_tab t5, pred_tab t6 WHERE t1.a = t3.a AND t6.a IS NOT NULL); - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Nested Loop Left Join - Join Filter: EXISTS(SubPlan exists_1) -> Seq Scan on pred_tab t1 - -> Materialize - -> Seq Scan on pred_tab t2 - SubPlan exists_1 - -> Nested Loop + -> Result + One-Time Filter: EXISTS(SubPlan exists_1) + -> Materialize + -> Seq Scan on pred_tab t2 + SubPlan exists_1 -> Nested Loop -> Nested Loop - -> Seq Scan on pred_tab t4 + -> Nested Loop + -> Seq Scan on pred_tab t4 + -> Materialize + -> Seq Scan on pred_tab t3 + Filter: (t1.a = a) -> Materialize - -> Seq Scan on pred_tab t3 - Filter: (t1.a = a) + -> Seq Scan on pred_tab t5 -> Materialize - -> Seq Scan on pred_tab t5 - -> Materialize - -> Seq Scan on pred_tab t6 -(17 rows) + -> Seq Scan on pred_tab t6 +(18 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE EXPLAIN (COSTS OFF) @@ -354,15 +361,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +392,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index cf295d56507..951dc8db589 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -3816,16 +3816,17 @@ EXPLAIN (COSTS OFF) SELECT * FROM not_null_tab t1 LEFT JOIN not_null_tab t2 ON t1.id NOT IN (SELECT id FROM not_null_tab); - QUERY PLAN ------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Nested Loop Left Join - Join Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) -> Seq Scan on not_null_tab t1 - -> Materialize - -> Seq Scan on not_null_tab t2 - SubPlan any_1 - -> Seq Scan on not_null_tab -(7 rows) + -> Result + One-Time Filter: (NOT (ANY (t1.id = (hashed SubPlan any_1).col1))) + -> Materialize + -> Seq Scan on not_null_tab t2 + SubPlan any_1 + -> Seq Scan on not_null_tab +(8 rows) -- ANTI JOIN: outer side is defined NOT NULL and is not nulled by outer join, -- inner side is defined NOT NULL diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index c30fd339f13..99ca02bc43d 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -4389,3 +4389,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.55.0
v3-0002-pg_plan_advice-look-through-gating-Results-on-the.patch (text/plain, 1.8K) download From 65f97b4d8eafea7b0f8a5878f367f8df6188817c Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 11 Sep 2026 16:39:31 +0200 Subject: [PATCH v3 2/2] pg_plan_advice: look through gating Results on the NestLoop inner side The preceding commit introduced a new plan shape: the inner side of a NestLoop may now be capped by a gating Result that evaluates outer-only join clauses as a one-time filter, sitting above any Material or Memoize node. pgpa_decompose_join() was unaware of this. Teach the NestLoop case to descend through a gating Result before the strategy checks. This restores the node ordering the rest of the function expects and classifies the strategy as MATERIALIZE/MEMOIZE again. A childless Result is deliberately not descended: it is itself the scan and carries its own RTIs. --- contrib/pg_plan_advice/pgpa_join.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contrib/pg_plan_advice/pgpa_join.c b/contrib/pg_plan_advice/pgpa_join.c index e69c25551a0..f3f2ad62f7c 100644 --- a/contrib/pg_plan_advice/pgpa_join.c +++ b/contrib/pg_plan_advice/pgpa_join.c @@ -388,6 +388,16 @@ pgpa_decompose_join(pgpa_plan_walker_context *walker, Plan *plan, case T_NestLoop: + /* + * create_nestloop_plan() may have capped the inner side with a + * gating Result that evaluates outer-only join clauses as a + * one-time filter. It sits above any Material or Memoize node, + * so look through it before determining the join strategy. + */ + if (elidedinner == NULL && is_result_node_with_child(innerplan) && + ((Result *) innerplan)->resconstantqual != NULL) + elidedinner = pgpa_descend_node(pstmt, &innerplan); + /* * The planner may have chosen to place a Material or Memoize node * on the inner side of the NestLoop; if this is present, we -- 2.55.0
^ permalink raw reply [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-09-14 16:26  Bryan Green <dbryan.green@gmail.com>
  parent: Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 23+ messages in thread

From: Bryan Green @ 2026-09-14 16:26 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>

On 9/12/2026 7:02 AM, Andrei Lepikhov wrote:
> On 01/09/2026 11:16, Andrei Lepikhov wrote:
>> On 28/07/2026 10:13, Andrei Lepikhov wrote:
>>
>> Just a rebase onto current master
>>
> 
> Another rebase to follow the master branch.
> 
> I have also looked at the downside of the opportunistic approach this feature
> takes. The pros are obvious: zero planning overhead, no search-space blowup, and
> simple code. But what does the worst case look like?
> 
> By gating the inner side, we add one more node (Result) and force the gating
> qual to be evaluated once per outer row. The vanilla NestLoop sometimes does not
> do that: when the inner side returns no tuple, a LEFT join goes straight to the
> null-fill path and ExecQual(joinqual) is never reached at all. So the gated plan
> pays for the clause on every outer row. I think a parameterised index scan that
> finds no match is the common case for this behaviour.
> 
> The worst query therefore looks like this:
> 
> CREATE TABLE o (a int, t text);
> INSERT INTO o SELECT g, 'row'||g FROM generate_series(1,1000000) g;
> CREATE TABLE i (a int, b int);
> ANALYZE o, i;
> 
> SET enable_hashjoin = off;
> SET enable_mergejoin = off;
> SET max_parallel_workers_per_gather = 0;
> \timing on
> 
> SELECT count(*) FROM ( SELECT * FROM o
>   LEFT JOIN i ON (md5(md5(md5(md5(o.t)))) <> 'z')) s;
> 
> Making the gate progressively more expensive shows what is going on.
> On the current master, I see ~470ms, with the gating clause ~1500ms. This effect
> is linear but isn't limited; it depends on the number of evaluations and the
> outer size.
> 
> The basic case, when each row passes the gate (and correspondent join clause)
> doesn't show any degradation, there are no significant difference between gated
> and no-gated approach. To reproduce just add one row into the inner table and
> re-execute the query above:
> 
> INSERT INTO i (a,b) VALUES (1, 1);
> 
> My conclusion is this. A gated NestLoop usually behaves like a normal NestLoop
> adding benefit of reduced inner scans or nothing. In the degenerate case where
> the inner side returns nothing, it adds an overhead proportional to the outer
> size times the cost of the gating clause, with no ceiling. Separately, the
> Result projection adds a per-joined- tuple cost that grows with the width of the
> inner targetlist.
> 
> I do not see this as a fundamental problem, except for SubPlan cases - but
> SubPlan is a different animal, and every new correlated pull-up technique
> attracts complaints of exactly this shape.
> 
> So the real question is whether the cost model can account for these two terms
> well enough to choose between a gated and a non-gated NestLoop, assuming we turn
> this into a cost-based optimisation.
> 
I've continued doing security audits of commitfest patches, and as part
of that I occasionally turn up differences in output that aren't
security issues but seemed worth passing along.  v3 has a few.  They all
show up on the gated nestloop plan, so I forced it with:

  set enable_hashjoin = off;
  set enable_mergejoin = off;

1) A left join that returns a row on HEAD raises an error with the patch:

  create table o (k int, x int); insert into o values (1, 0);
  create table i (k int);                       -- empty
  select * from o left join i on o.k = i.k and 1/o.x = 1;
  --  HEAD:  (1, 0, NULL)
  --  v3:    ERROR:  division by zero

2) A volatile condition returns a different number of rows:

  create table a (k int, x int); insert into a values (1, 2);
  create table b (k int, y int); insert into b values
(1,1),(1,2),(1,3),(1,4);
  create sequence s;
  select a.k, b.y from a left join b on a.k = b.k and a.x > nextval('s');
  --  HEAD:  1 row
  --  v3:    4 rows

3) The same when the volatile is inside a sub-select:

  alter sequence s restart;
  select a.k, b.y from a left join b
    on a.k = b.k and a.x > (select nextval('s') where a.k = 1);
  --  HEAD:  1 row
  --  v3:    4 rows

On HEAD I get the same answers under hash and merge joins as well, so
these aren't just plan-to-plan variation.  I haven't worked out whether
any of them matter for what you're doing here.  Passing them along in
case they do.

-- 
Bryan Green
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 23+ messages in thread

* Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
@ 2026-09-15 09:59  Andrei Lepikhov <lepihov@gmail.com>
  parent: Bryan Green <dbryan.green@gmail.com>
  0 siblings, 0 replies; 23+ messages in thread

From: Andrei Lepikhov @ 2026-09-15 09:59 UTC (permalink / raw)
  To: Bryan Green <dbryan.green@gmail.com>; +Cc: Илья Жарков <izharkov1243@gmail.com>; pgsql-hackers@lists.postgresql.org, eng eng <pspetrov91@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>

On 14/09/2026 18:26, Bryan Green wrote:
> On 9/12/2026 7:02 AM, Andrei Lepikhov wrote:
>> On 01/09/2026 11:16, Andrei Lepikhov wrote:
>> So the real question is whether the cost model can account for these two terms
>> well enough to choose between a gated and a non-gated NestLoop, assuming we turn
>> this into a cost-based optimisation.
>>
> I've continued doing security audits of commitfest patches, and as part
> of that I occasionally turn up differences in output that aren't
> security issues but seemed worth passing along.  v3 has a few.  They all
> show up on the gated nestloop plan, so I forced it with:
> 
>   set enable_hashjoin = off;
>   set enable_mergejoin = off;
> 
> 1) A left join that returns a row on HEAD raises an error with the patch:
> 
>   create table o (k int, x int); insert into o values (1, 0);
>   create table i (k int);                       -- empty
>   select * from o left join i on o.k = i.k and 1/o.x = 1;
>   --  HEAD:  (1, 0, NULL)
>   --  v3:    ERROR:  division by zero

That’s a false positive. I believe I addressed this topic thoroughly in my blog
post [1] to prevent such comments ;). Please take a look and let me know if you
have any further questions.

> 
> 2) A volatile condition returns a different number of rows:
> 
>   create table a (k int, x int); insert into a values (1, 2);
>   create table b (k int, y int); insert into b values
> (1,1),(1,2),(1,3),(1,4);
>   create sequence s;
>   select a.k, b.y from a left join b on a.k = b.k and a.x > nextval('s');
>   --  HEAD:  1 row
>   --  v3:    4 rows

This is an actual catch. Postgres has a convention on pushdown safety,
implemented in qual_is_pushdown_safe, and I was wrong to ignore it. I believe
the new version of the first patch (attached) contains the necessary fixes.

[1]
https://www.pgedge.com/blog/binary-ternary-or-is-it-actually-quaternary-logic-in-postgres-functions

-- 
regards, Andrei Lepikhov,
pgEdge

Attachments:

v4-0001-Gate-the-NestLoop-inner-side-with-outer-only-join.patch (text/plain, 48.2K) download From ea8a852ab3588f3f9937edb47877da956f9e63c3 Mon Sep 17 00:00:00 2001 From: "Andrei V. Lepikhov" <lepihov@gmail.com> Date: Fri, 11 Sep 2026 16:39:23 +0200 Subject: [PATCH v4 1/2] Gate the NestLoop inner side with outer-only join clauses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In some cases, a LEFT JOIN’s NestLoop might have a clause that depends only on the outer side of the join. In such a case, if the outer tuple evaluates this clause as false, the result of the inner side scan operation will not impact the join’s output: inner side will always be replaced with NULL values. Treat such an outer-side clause as a ‘gating’ clause and push it into the inner side as a Result node. It will reduce the number of rescan operations to a bare minimum when the the gating clause evaluates to a true. This operation effectively forces parameterisation of the NestLoop JOIN, even if it was originally plain. To identify such cases, the NestLoop struct was supplemented with a flag that allows the executor to distinguish a ‘gated’ join from the parameterised NestLoop and to set the REWIND flag correctly. No costing change is made: the gating Result inherits its child's cost fields, and final_cost_nestloop() does not model the skipped inner rescans. --- .../postgres_fdw/expected/postgres_fdw.out | 14 +- src/backend/executor/nodeNestloop.c | 12 +- src/backend/optimizer/plan/createplan.c | 104 ++++- src/include/nodes/plannodes.h | 2 + src/test/regress/expected/create_index.out | 21 +- src/test/regress/expected/join.out | 412 ++++++++++-------- src/test/regress/expected/predicate.out | 84 ++-- src/test/regress/sql/join.sql | 27 ++ 8 files changed, 446 insertions(+), 230 deletions(-) diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out index a6295674daf..8421c37f8de 100644 --- a/contrib/postgres_fdw/expected/postgres_fdw.out +++ b/contrib/postgres_fdw/expected/postgres_fdw.out @@ -2532,16 +2532,18 @@ SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 O --------------------------------------------------------------------------------------------------------------------------- Nested Loop Left Join Output: (13), ft2.c1 - Join Filter: (13 = ft2.c1) -> Foreign Scan on public.ft2 Output: ft2.c1 Remote SQL: SELECT "C 1" FROM "S 1"."T 1" WHERE (("C 1" >= 10)) AND (("C 1" <= 15)) ORDER BY "C 1" ASC NULLS LAST - -> Materialize + -> Result Output: (13) - -> Foreign Scan on public.ft1 - Output: 13 - Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) -(11 rows) + One-Time Filter: (13 = ft2.c1) + -> Materialize + Output: (13) + -> Foreign Scan on public.ft1 + Output: 13 + Remote SQL: SELECT NULL FROM "S 1"."T 1" WHERE (("C 1" = 13)) +(13 rows) SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; a | c1 diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index da48c9b204b..7da6eb49fc1 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -263,12 +263,16 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) * * If we have no parameters to pass into the inner rel from the outer, * tell the inner child that cheap rescans would be good. If we do have - * such parameters, then there is no point in REWIND support at all in the - * inner child, because it will always be rescanned with fresh parameter - * values. + * such parameters, there is normally no point in REWIND support in the + * inner child, because it will be rescanned with fresh parameter values. + * + * The exception is a 'gated' nested loop join, where the only parameters + * feed a gating Result that caps the inner subtree and is re-checked once + * per outer tuple. The plan below that gate is parameter-independent, so + * we keep the REWIND flag. */ outerPlanState(nlstate) = ExecInitNode(outerPlan(node), estate, eflags); - if (node->nestParams == NIL) + if (node->nestParams == NIL || node->keep_inner_rewind) eflags |= EXEC_FLAG_REWIND; else eflags &= ~EXEC_FLAG_REWIND; diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c index 430f6557f1f..0e76537bae0 100644 --- a/src/backend/optimizer/plan/createplan.c +++ b/src/backend/optimizer/plan/createplan.c @@ -4201,8 +4201,11 @@ create_nestloop_plan(PlannerInfo *root, Relids outerrelids; Relids req_outer; Relids ojrelids; + Relids joinrelids = best_path->jpath.path.parent->relids; List *tlist = build_path_tlist(root, &best_path->jpath.path); List *joinrestrictclauses = best_path->jpath.joinrestrictinfo; + List *gating_clauses = NIL; + bool keep_inner_rewind = false; List *joinclauses; List *otherclauses; List *nestParams; @@ -4257,8 +4260,35 @@ create_nestloop_plan(PlannerInfo *root, if (IS_OUTER_JOIN(best_path->jpath.jointype)) { extract_actual_join_clauses(joinrestrictclauses, - best_path->jpath.path.parent->relids, + joinrelids, &joinclauses, &otherclauses); + + /* + * Collect the join clauses that reference only the outer rel: they + * are constant for a given outer tuple, so the loop further down can + * gate the inner side with them instead of re-checking them per inner + * row. + */ + foreach_node(RestrictInfo, rinfo, joinrestrictclauses) + { + if (bms_is_empty(rinfo->clause_relids) || + !bms_is_subset(rinfo->clause_relids, outerrelids)) + continue; + + /* + * Gating evaluates the clause once per outer tuple instead of once + * per join-candidate pair. That is only transparent if the clause + * yields the same answer every time. Hence, refuse volatile + * expressions and SubPlans whose own evaluation count would change. + */ + if (contain_volatile_functions((Node *) rinfo) || + contain_subplans((Node *) rinfo->clause)) + continue; + + Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)); + + gating_clauses = lappend(gating_clauses, rinfo->clause); + } } else { @@ -4267,6 +4297,14 @@ create_nestloop_plan(PlannerInfo *root, otherclauses = NIL; } + /* + * Pull the outer-only clauses out of joinclauses; they become a gating + * qual on the inner side below. Do this before parameterization, while + * the expressions are still un-parameterized. + */ + if (gating_clauses != NIL) + joinclauses = list_difference_ptr(joinclauses, gating_clauses); + /* Replace any outer-relation variables with nestloop params */ if (best_path->jpath.path.param_info) { @@ -4302,6 +4340,68 @@ create_nestloop_plan(PlannerInfo *root, } } + /* + * The gating clauses must be parameterized so the gating Result can + * evaluate them against the current outer tuple. + */ + if (gating_clauses != NIL) + { + Relids tmpOuterRels = root->curOuterRels; + Plan *subplan = inner_plan; + + /* + * Keep the inner side rewindable across rescans, but only when this + * gate is the sole source of nestloop parameters. + */ + keep_inner_rewind = + !bms_overlap(PATH_REQ_OUTER(best_path->jpath.innerjoinpath), + outerrelids); + + Assert(bms_is_subset(pull_varnos(root, (Node *) gating_clauses), + outerrelids)); + + /* + * replace_nestloop_params only converts Vars in curOuterRels, which + * was restored above and no longer covers this join's outer relids, + * so re-add them across the call. + */ + root->curOuterRels = bms_union(root->curOuterRels, outerrelids); + gating_clauses = (List *) + replace_nestloop_params(root, (Node *) gating_clauses); + bms_free(root->curOuterRels); + root->curOuterRels = tmpOuterRels; + + /* + * Avoid stacking Result nodes. If the inner plan is already a + * Result, merge our parameterized clauses into its resconstantqual. + * This mirrors create_gating_plan()'s logic. + */ + if (IsA(subplan, Result)) + { + Result *existing = (Result *) subplan; + List *clauses = (List *) existing->resconstantqual; + + Assert(clauses == NULL || IsA(clauses, List)); + + clauses = list_concat(gating_clauses, clauses); + clauses = order_qual_clauses(root, clauses); + existing->resconstantqual = (Node *) clauses; + + /* Gating quals could be unsafe, so use the Path's safety flag */ + existing->plan.parallel_safe = best_path->jpath.path.parallel_safe; + } + else + { + inner_plan = (Plan *) make_gating_result(subplan->targetlist, + (Node *) gating_clauses, + subplan); + copy_plan_costsize(inner_plan, subplan); + + /* Gating quals could be unsafe, so use the Path's safety flag */ + inner_plan->parallel_safe = best_path->jpath.path.parallel_safe; + } + } + /* * Identify any nestloop parameters that should be supplied by this join * node, and remove them from root->curOuterParams. @@ -4374,6 +4474,8 @@ create_nestloop_plan(PlannerInfo *root, ojrelids, best_path->jpath.inner_unique); + join_plan->keep_inner_rewind = keep_inner_rewind; + copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path); return join_plan; diff --git a/src/include/nodes/plannodes.h b/src/include/nodes/plannodes.h index 2fe6b61afaf..dce46966685 100644 --- a/src/include/nodes/plannodes.h +++ b/src/include/nodes/plannodes.h @@ -1010,6 +1010,8 @@ typedef struct NestLoop Join join; /* list of NestLoopParam nodes */ List *nestParams; + /* keep inner side rewindable: gate is the sole source of nestloop params */ + bool keep_inner_rewind; } NestLoop; typedef struct NestLoopParam diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/expected/create_index.out index 7b2640f0e04..f9db7416306 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2260,19 +2260,20 @@ EXPLAIN (COSTS OFF) SELECT count(*) FROM tenk1 LEFT JOIN tenk2 ON tenk1.hundred = 42 AND (tenk2.thousand = 42 OR tenk2.thousand = 41 OR tenk2.tenthous = 2) AND tenk2.hundred = tenk1.hundred; - QUERY PLAN ------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------ Aggregate -> Nested Loop Left Join - Join Filter: (tenk1.hundred = 42) -> Index Only Scan using tenk1_hundred on tenk1 - -> Memoize - Cache Key: tenk1.hundred - Cache Mode: logical - -> Index Scan using tenk2_hundred on tenk2 - Index Cond: (hundred = tenk1.hundred) - Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) -(10 rows) + -> Result + One-Time Filter: (tenk1.hundred = 42) + -> Memoize + Cache Key: tenk1.hundred + Cache Mode: logical + -> Index Scan using tenk2_hundred on tenk2 + Index Cond: (hundred = tenk1.hundred) + Filter: ((thousand = 42) OR (thousand = 41) OR (tenthous = 2)) +(11 rows) -- -- Check behavior with duplicate index column contents diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 75544fe6aa3..ff471050093 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -2424,21 +2424,22 @@ from int4_tbl t1, int4_tbl t2 left join int4_tbl t3 on t3.f1 > 0 left join int4_tbl t4 on t3.f1 > 1 where t4.f1 is null; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop -> Nested Loop Left Join Filter: (t4.f1 IS NULL) -> Seq Scan on int4_tbl t2 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 1) -> Seq Scan on int4_tbl t3 Filter: (f1 > 0) - -> Materialize - -> Seq Scan on int4_tbl t4 + -> Result + One-Time Filter: (t3.f1 > 1) + -> Materialize + -> Seq Scan on int4_tbl t4 -> Seq Scan on int4_tbl t1 -(12 rows) +(13 rows) select t1.f1 from int4_tbl t1, int4_tbl t2 @@ -2454,21 +2455,23 @@ select * from int4_tbl t1 left join int4_tbl t2 on true left join int4_tbl t3 on t2.f1 > 0 left join int4_tbl t4 on t3.f1 > 0; - QUERY PLAN -------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int4_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.f1 > 0) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Seq Scan on int4_tbl t2 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t3.f1 > 0) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(12 rows) + -> Seq Scan on int4_tbl t4 +(14 rows) explain (costs off) select * from onek t1 @@ -2525,7 +2528,6 @@ select * from int4_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 = t3.f1) -> Nested Loop Left Join -> Nested Loop Left Join -> Seq Scan on int4_tbl t1 @@ -2533,9 +2535,11 @@ select * from int4_tbl t1 -> Seq Scan on int4_tbl t2 -> Materialize -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(11 rows) + -> Result + One-Time Filter: (t2.f1 = t3.f1) + -> Materialize + -> Seq Scan on int4_tbl t4 +(12 rows) explain (costs off) select * from int4_tbl t1 @@ -2563,23 +2567,25 @@ select * from int4_tbl t1 left join (int4_tbl t2 left join int4_tbl t3 on t2.f1 > 0) on t2.f1 > 1 left join int4_tbl t4 on t2.f1 > 2 and t3.f1 > 3 where t1.f1 = coalesce(t2.f1, 1); - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) -> Nested Loop Left Join Filter: (t1.f1 = COALESCE(t2.f1, 1)) -> Seq Scan on int4_tbl t1 -> Materialize -> Seq Scan on int4_tbl t2 Filter: (f1 > 1) + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: ((t2.f1 > 2) AND (t3.f1 > 3)) -> Materialize - -> Seq Scan on int4_tbl t3 - -> Materialize - -> Seq Scan on int4_tbl t4 -(14 rows) + -> Seq Scan on int4_tbl t4 +(16 rows) explain (costs off) select * from int4_tbl t1 @@ -2588,22 +2594,24 @@ select * from int4_tbl t1 where t3.f1 is null) s left join tenk1 t4 on s.f1 > 1) on s.f1 = t1.f1; - QUERY PLAN -------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t3.f1 IS NULL) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 - -> Seq Scan on tenk1 t4 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 1) + -> Seq Scan on tenk1 t4 -> Hash -> Seq Scan on int4_tbl t1 -(13 rows) +(15 rows) explain (costs off) select * from int4_tbl t1 @@ -2615,20 +2623,22 @@ select * from int4_tbl t1 QUERY PLAN ----------------------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.f1 > 1) -> Hash Right Join Hash Cond: (t2.f1 = t1.f1) -> Nested Loop Left Join - Join Filter: (t2.f1 > 0) Filter: (t2.f1 <> COALESCE(t3.f1, '-1'::integer)) -> Seq Scan on int4_tbl t2 - -> Materialize - -> Seq Scan on int4_tbl t3 + -> Result + One-Time Filter: (t2.f1 > 0) + -> Materialize + -> Seq Scan on int4_tbl t3 -> Hash -> Seq Scan on int4_tbl t1 - -> Materialize - -> Seq Scan on tenk1 t4 -(14 rows) + -> Result + One-Time Filter: (t2.f1 > 1) + -> Materialize + -> Seq Scan on tenk1 t4 +(16 rows) explain (costs off) select * from onek t1 @@ -2680,17 +2690,18 @@ select * from int8_tbl t1 left join lateral (select * from int8_tbl t3 where t3.q1 = t2.q1 offset 0) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 - Filter: (q1 = t2.q1) -(8 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 + Filter: (q1 = t2.q1) +(9 rows) explain (costs off) select * from int8_tbl t1 @@ -2698,16 +2709,17 @@ select * from int8_tbl t1 left join lateral (select * from generate_series(t2.q1, 100)) s on t2.q1 = 1; - QUERY PLAN ----------------------------------------------------- + QUERY PLAN +---------------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Function Scan on generate_series -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Function Scan on generate_series +(8 rows) explain (costs off) select * from int8_tbl t1 @@ -2715,16 +2727,17 @@ select * from int8_tbl t1 left join lateral (select t2.q1 from int8_tbl t3) s on t2.q1 = 1; - QUERY PLAN -------------------------------------------- + QUERY PLAN +-------------------------------------------------- Nested Loop Left Join -> Seq Scan on int8_tbl t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.q1 = 1) -> Seq Scan on int8_tbl t2 - -> Seq Scan on int8_tbl t3 -(7 rows) + -> Result + One-Time Filter: (t2.q1 = 1) + -> Seq Scan on int8_tbl t3 +(8 rows) explain (costs off) select * from onek t1 @@ -2732,20 +2745,21 @@ select * from onek t1 left join lateral (select * from onek t3 where t3.two = t2.two offset 0) s on t2.unique1 = 1; - QUERY PLAN --------------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join -> Seq Scan on onek t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.unique1 = 1) -> Seq Scan on onek t2 - -> Memoize - Cache Key: t2.two - Cache Mode: binary - -> Seq Scan on onek t3 - Filter: (two = t2.two) -(11 rows) + -> Result + One-Time Filter: (t2.unique1 = 1) + -> Memoize + Cache Key: t2.two + Cache Mode: binary + -> Seq Scan on onek t3 + Filter: (two = t2.two) +(12 rows) -- -- check a case where we formerly got confused by conflicting sort orders @@ -5465,11 +5479,12 @@ select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; QUERY PLAN ---------------------------------------------------- Nested Loop Left Join - Join Filter: (tenk1.unique1 = 1) -> Index Only Scan using tenk1_unique1 on tenk1 - -> Materialize - -> Result -(5 rows) + -> Result + One-Time Filter: (tenk1.unique1 = 1) + -> Materialize + -> Result +(6 rows) explain (costs off) select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; @@ -5516,17 +5531,17 @@ from nt3 as nt3 ) as ss2 on ss2.id = nt3.nt2_id where nt3.id = 1 and ss2.b3; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join Filter: ((nt2.b1 OR ((0) = 42))) -> Index Scan using nt3_pkey on nt3 Index Cond: (id = 1) -> Nested Loop Left Join - Join Filter: (0 = nt2.nt1_id) -> Index Scan using nt2_pkey on nt2 Index Cond: (id = nt3.nt2_id) -> Result + One-Time Filter: (0 = nt2.nt1_id) (9 rows) drop function f_immutable_int4(int); @@ -5766,7 +5781,6 @@ select count(*) from ------------------------------------------------------------------------- Aggregate -> Nested Loop Left Join - Join Filter: (a.unique2 = b.unique1) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl @@ -5776,9 +5790,11 @@ select count(*) from Index Cond: (thousand = int4_tbl.f1) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(14 rows) + -> Result + One-Time Filter: (a.unique2 = b.unique1) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(15 rows) select count(*) from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -5803,7 +5819,6 @@ select b.unique1 from -> Nested Loop Left Join -> Seq Scan on int4_tbl i2 -> Nested Loop Left Join - Join Filter: (b.unique1 = 42) -> Nested Loop -> Nested Loop -> Seq Scan on int4_tbl i1 @@ -5811,9 +5826,11 @@ select b.unique1 from Index Cond: ((thousand = i1.f1) AND (tenthous = i2.f1)) -> Index Scan using tenk1_unique1 on tenk1 a Index Cond: (unique1 = b.unique2) - -> Index Only Scan using tenk1_thous_tenthous on tenk1 c - Index Cond: (thousand = a.thousand) -(15 rows) + -> Result + One-Time Filter: (b.unique1 = 42) + -> Index Only Scan using tenk1_thous_tenthous on tenk1 c + Index Cond: (thousand = a.thousand) +(16 rows) select b.unique1 from tenk1 a join tenk1 b on a.unique1 = b.unique2 @@ -6112,39 +6129,41 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) - -> Hash Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8.q1 = i8b2.q1) - -> Seq Scan on public.int8_tbl i8 - Output: i8.q1, i8.q2 + -> Hash Right Join + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8.q1 = i8b2.q1) + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash + Output: i8b2.q1, (NULL::integer) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, NULL::integer -> Hash - Output: i8b2.q1, (NULL::integer) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, NULL::integer - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(30 rows) +(32 rows) select t1.* from text_tbl t1 @@ -6173,43 +6192,45 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Nested Loop - Output: i8b2.q1, NULL::integer - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Materialize - -> Seq Scan on public.int4_tbl i4b2 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Nested Loop + Output: i8b2.q1, NULL::integer + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Materialize + -> Seq Scan on public.int4_tbl i4b2 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(34 rows) +(36 rows) select t1.* from text_tbl t1 @@ -6239,46 +6260,48 @@ select t1.* from on (t1.f1 = b1.d1) left join int4_tbl i4 on (i8.q2 = i4.f1); - QUERY PLAN ----------------------------------------------------------------------------- + QUERY PLAN +---------------------------------------------------------------------------------- Hash Left Join Output: t1.f1 Hash Cond: (i8.q2 = i4.f1) -> Nested Loop Left Join Output: t1.f1, i8.q2 - Join Filter: (t1.f1 = '***'::text) -> Seq Scan on public.text_tbl t1 Output: t1.f1 - -> Materialize + -> Result Output: i8.q2 - -> Hash Right Join + One-Time Filter: (t1.f1 = '***'::text) + -> Materialize Output: i8.q2 - Hash Cond: ((NULL::integer) = i8b1.q2) -> Hash Right Join - Output: i8.q2, (NULL::integer) - Hash Cond: (i8b2.q1 = i8.q1) - -> Hash Join - Output: i8b2.q1, NULL::integer - Hash Cond: (i8b2.q1 = i4b2.f1) - -> Seq Scan on public.int8_tbl i8b2 - Output: i8b2.q1, i8b2.q2 - -> Hash - Output: i4b2.f1 - -> Seq Scan on public.int4_tbl i4b2 + Output: i8.q2 + Hash Cond: ((NULL::integer) = i8b1.q2) + -> Hash Right Join + Output: i8.q2, (NULL::integer) + Hash Cond: (i8b2.q1 = i8.q1) + -> Hash Join + Output: i8b2.q1, NULL::integer + Hash Cond: (i8b2.q1 = i4b2.f1) + -> Seq Scan on public.int8_tbl i8b2 + Output: i8b2.q1, i8b2.q2 + -> Hash Output: i4b2.f1 - -> Hash - Output: i8.q1, i8.q2 - -> Seq Scan on public.int8_tbl i8 + -> Seq Scan on public.int4_tbl i4b2 + Output: i4b2.f1 + -> Hash Output: i8.q1, i8.q2 - -> Hash - Output: i8b1.q2 - -> Seq Scan on public.int8_tbl i8b1 + -> Seq Scan on public.int8_tbl i8 + Output: i8.q1, i8.q2 + -> Hash Output: i8b1.q2 + -> Seq Scan on public.int8_tbl i8b1 + Output: i8b1.q2 -> Hash Output: i4.f1 -> Seq Scan on public.int4_tbl i4 Output: i4.f1 -(37 rows) +(39 rows) select t1.* from text_tbl t1 @@ -6372,8 +6395,8 @@ select 1 from join int4_tbl i42 on ss1.a is null or i8.q1 <> i8.q2 right join (select 2 as b) ss2 on ss2.b < i4.f1; - QUERY PLAN ------------------------------------------------------------ + QUERY PLAN +---------------------------------------------------------------- Nested Loop Left Join -> Result -> Nested Loop @@ -6381,16 +6404,17 @@ select 1 from Join Filter: NULL::boolean Filter: (((1) IS NULL) OR (i8.q1 <> i8.q2)) -> Nested Loop Left Join - Join Filter: (i4.f1 IS NOT NULL) -> Seq Scan on int4_tbl i4 Filter: (2 < f1) - -> Materialize - -> Seq Scan on int8_tbl i8 + -> Result + One-Time Filter: (i4.f1 IS NOT NULL) + -> Materialize + -> Seq Scan on int8_tbl i8 -> Result One-Time Filter: false -> Materialize -> Seq Scan on int4_tbl i42 -(16 rows) +(17 rows) -- -- test for appropriate join order in the presence of lateral references @@ -7229,7 +7253,6 @@ from int8_tbl t1 QUERY PLAN ------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.q2 < t3.unique2) -> Nested Loop Left Join Join Filter: (t2.q1 > t3.unique1) -> Hash Left Join @@ -7239,9 +7262,11 @@ from int8_tbl t1 -> Seq Scan on int8_tbl t2 -> Materialize -> Seq Scan on onek t3 - -> Materialize - -> Seq Scan on onek t4 -(13 rows) + -> Result + One-Time Filter: (t2.q2 < t3.unique2) + -> Materialize + -> Seq Scan on onek t4 +(14 rows) -- bug #19460: we need to clean up RestrictInfos more than we had been doing explain (costs off) @@ -7674,11 +7699,12 @@ select 1 from a t1 -> Seq Scan on a t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t2.id = 1) -> Index Only Scan using a_pkey on a t2 Index Cond: (id = 1) - -> Seq Scan on a t3 -(8 rows) + -> Result + One-Time Filter: (t2.id = 1) + -> Seq Scan on a t3 +(9 rows) -- check join removal works when uniqueness of the join condition is enforced -- by a UNION @@ -9258,14 +9284,15 @@ explain (costs off) select * from emp1 t1 inner join emp1 t2 on t1.id = t2.id left join emp1 t3 on t1.id > 1 and t1.id < 2; - QUERY PLAN ----------------------------------------------- + QUERY PLAN +-------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.id > 1) AND (t2.id < 2)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: ((t2.id > 1) AND (t2.id < 2)) + -> Materialize + -> Seq Scan on emp1 t3 +(6 rows) -- Check that SJE doesn't replace the target relation EXPLAIN (COSTS OFF) @@ -9286,14 +9313,16 @@ EXPLAIN (COSTS OFF) SELECT * FROM emp1 t1 INNER JOIN emp1 t2 ON t1.id = t2.id LEFT JOIN emp1 t3 ON t1.code = 1 AND (t2.code = t3.code OR t2.code = 1); - QUERY PLAN ---------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.code = 1) AND ((t2.code = t3.code) OR (t2.code = 1))) + Join Filter: ((t2.code = t3.code) OR (t2.code = 1)) -> Seq Scan on emp1 t2 - -> Materialize - -> Seq Scan on emp1 t3 -(5 rows) + -> Result + One-Time Filter: (t2.code = 1) + -> Materialize + -> Seq Scan on emp1 t3 +(7 rows) INSERT INTO emp1 VALUES (1, 1), (2, 1); WITH t1 AS (SELECT * FROM emp1) @@ -9468,11 +9497,12 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) Nested Loop Left Join -> Seq Scan on sl sl1 -> Nested Loop Left Join - Join Filter: sl3.bool_col -> Seq Scan on sl sl3 Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) - -> Seq Scan on sl sl4 -(7 rows) + -> Result + One-Time Filter: sl3.bool_col + -> Seq Scan on sl sl4 +(8 rows) -- Check that quals of a jointree node that becomes empty when the self-join -- is removed are not lost, and that they don't migrate above an outer join @@ -11495,3 +11525,43 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 19000 (1 row) +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); + platform_independent_explain +---------------------------------------------------------------------------- + Aggregate (actual rows=1.00 loops=1) + -> Nested Loop Left Join (actual rows=1000.00 loops=1) + Join Filter: (t1.unique1 = t2.f1) + Rows Removed by Join Filter: 1000 + -> Seq Scan on onek t1 (actual rows=1000.00 loops=1) + -> Result (actual rows=1.00 loops=1000) + One-Time Filter: (t1.hundred = ANY ('{1,2}'::integer[])) + -> Materialize (actual rows=5.00 loops=200) + Storage: Memory Maximum Storage: NkB + -> Seq Scan on int4_tbl t2 (actual rows=5.00 loops=1) +(10 rows) + +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out index feae77cb840..ee1d87eca80 100644 --- a/src/test/regress/expected/predicate.out +++ b/src/test/regress/expected/predicate.out @@ -114,10 +114,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +--------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NOT NULL) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -126,9 +125,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: (t2.a IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the IS_NULL qual is reduced to constant-FALSE, since a) it's on a NOT -- NULL column, and b) its Var is not nullable by any outer joins @@ -151,18 +152,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL; - QUERY PLAN -------------------------------------------- + QUERY PLAN +------------------------------------------------- Nested Loop Left Join - Join Filter: (t2.a IS NULL) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: (t2.a IS NULL) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for OR clauses in join clauses @@ -185,10 +188,9 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 FULL JOIN pred_tab t2 ON t1.a = t2.a LEFT JOIN pred_tab t3 ON t2.a IS NOT NULL OR t2.b = 1; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) -> Merge Full Join Merge Cond: (t1.a = t2.a) -> Sort @@ -197,9 +199,11 @@ SELECT * FROM pred_tab t1 -> Sort Sort Key: t2.a -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(12 rows) + -> Result + One-Time Filter: ((t2.a IS NOT NULL) OR (t2.b = 1)) + -> Materialize + -> Seq Scan on pred_tab t3 +(13 rows) -- Ensure the OR clause is reduced to constant-FALSE when all OR branches are -- provably false @@ -222,18 +226,20 @@ EXPLAIN (COSTS OFF) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON t1.a = 1 LEFT JOIN pred_tab t3 ON t2.a IS NULL OR t2.c IS NULL; - QUERY PLAN ---------------------------------------------------- + QUERY PLAN +------------------------------------------------------------- Nested Loop Left Join - Join Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Nested Loop Left Join - Join Filter: (t1.a = 1) -> Seq Scan on pred_tab t1 + -> Result + One-Time Filter: (t1.a = 1) + -> Materialize + -> Seq Scan on pred_tab t2 + -> Result + One-Time Filter: ((t2.a IS NULL) OR (t2.c IS NULL)) -> Materialize - -> Seq Scan on pred_tab t2 - -> Materialize - -> Seq Scan on pred_tab t3 -(9 rows) + -> Seq Scan on pred_tab t3 +(11 rows) -- -- Tests for NullTest reduction in EXISTS sublink @@ -354,15 +360,16 @@ SELECT * FROM pred_tab t1 -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: (t3.b IS NOT NULL) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: (t3.b IS NOT NULL) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE @@ -384,21 +391,22 @@ SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE LEFT JOIN pred_tab_notnull t3 ON t2.a = t3.a LEFT JOIN pred_tab t4 ON t3.b IS NULL AND t3.a IS NOT NULL; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------ Nested Loop Left Join -> Seq Scan on pred_tab t1 -> Materialize -> Nested Loop Left Join - Join Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) -> Nested Loop Left Join Join Filter: (t2.a = t3.a) -> Seq Scan on pred_tab t2 -> Materialize -> Seq Scan on pred_tab_notnull t3 - -> Materialize - -> Seq Scan on pred_tab t4 -(12 rows) + -> Result + One-Time Filter: ((t3.b IS NULL) AND (t3.a IS NOT NULL)) + -> Materialize + -> Seq Scan on pred_tab t4 +(13 rows) SELECT * FROM pred_tab t1 LEFT JOIN pred_tab t2 ON TRUE diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index fb83a96e939..96ef40d186e 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -4436,3 +4436,30 @@ SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); SELECT COUNT(*) FROM onek t1 LEFT JOIN tenk1 t2 ON (t2.thousand = t1.tenthous OR t2.thousand = t1.thousand); + +-- Outer-only ON-clauses become a gating Result on the inner side; for a +-- parameter-independent inner, NestLoop.keep_inner_rewind retains REWIND so +-- a Materialize below the gate replays its buffer across rescans rather than +-- rebuilding it for every outer tuple that passes the gate. +create function platform_independent_explain(query text) returns setof text +language plpgsql as +$$ +declare + ln text; +begin + for ln in + execute format('explain (analyze, costs off, summary off, timing off, buffers off) %s', query) + loop + ln := regexp_replace(ln, 'Maximum Storage: \d+', 'Maximum Storage: N'); + return next ln; + end loop; +end; +$$; +set enable_hashjoin = off; +set enable_mergejoin = off; +select platform_independent_explain(' + select count(*) from onek t1 left join int4_tbl t2 + on (t1.unique1 = t2.f1 and t1.hundred in (1, 2))'); +reset enable_hashjoin; +reset enable_mergejoin; +drop function platform_independent_explain(text); -- 2.55.0
^ permalink raw reply [nested|flat] 23+ messages in thread


end of thread, other threads:[~2026-09-15 09:59 UTC | newest]

Thread overview: 23+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-12-07 18:30 Do not scan index in right table if condition for left join evaluates to false using columns in left table Илья Жарков <izharkov1243@gmail.com>
2024-12-07 21:37 ` Andres Freund <andres@anarazel.de>
2024-12-07 22:06   ` Tom Lane <tgl@sss.pgh.pa.us>
2024-12-07 23:07     ` Andres Freund <andres@anarazel.de>
2024-12-07 23:13       ` Tom Lane <tgl@sss.pgh.pa.us>
2024-12-08 02:23         ` Andrei Lepikhov <lepihov@gmail.com>
2024-12-08 02:52           ` Andres Freund <andres@anarazel.de>
2024-12-08 03:11             ` Tom Lane <tgl@sss.pgh.pa.us>
2024-12-08 08:44             ` Andrei Lepikhov <lepihov@gmail.com>
2024-12-08 15:24               ` Илья Жарков <izharkov1243@gmail.com>
2024-12-08 16:37               ` Andres Freund <andres@anarazel.de>
2024-12-09 02:35                 ` Andrei Lepikhov <lepihov@gmail.com>
2024-12-16 09:58           ` eng eng <pspetrov91@gmail.com>
2026-05-27 10:11             ` Andrei Lepikhov <lepihov@gmail.com>
2026-06-30 08:20               ` Andrei Lepikhov <lepihov@gmail.com>
2026-07-03 10:53                 ` Andrei Lepikhov <lepihov@gmail.com>
2026-07-28 08:13                   ` Andrei Lepikhov <lepihov@gmail.com>
2026-09-01 09:16                     ` Andrei Lepikhov <lepihov@gmail.com>
2026-09-12 12:02                       ` Andrei Lepikhov <lepihov@gmail.com>
2026-09-14 16:26                         ` Bryan Green <dbryan.green@gmail.com>
2026-09-15 09:59                           ` Andrei Lepikhov <lepihov@gmail.com>
2024-12-07 22:21   ` Andres Freund <andres@anarazel.de>
2024-12-07 23:04     ` Илья Жарков <izharkov1243@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox