From 83fd58dff02f4f1912c87194d8f9db7fe9e644c4 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Tue, 24 Sep 2002 18:38:23 +0000
Subject: [PATCH] Add missing correction of sublevelsup when pulling up a
 subquery. Fixes problem with cases like SELECT * FROM foo t WHERE NOT EXISTS
 (SELECT remoteid FROM (SELECT f1 as remoteid FROM foo WHERE f1 = t.f1) AS t1)

---
 src/backend/optimizer/plan/planner.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 5510a74957..b607173a4c 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -8,7 +8,7 @@
  *
  *
  * IDENTIFICATION
- *	  $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.124 2002/09/04 20:31:21 momjian Exp $
+ *	  $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.125 2002/09/24 18:38:23 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -337,17 +337,23 @@ pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
 
 			/*
 			 * Now make a modifiable copy of the subquery that we can run
-			 * OffsetVarNodes on.
+			 * OffsetVarNodes and IncrementVarSublevelsUp on.
 			 */
 			subquery = copyObject(subquery);
 
 			/*
-			 * Adjust varnos in subquery so that we can append its
+			 * Adjust level-0 varnos in subquery so that we can append its
 			 * rangetable to upper query's.
 			 */
 			rtoffset = length(parse->rtable);
 			OffsetVarNodes((Node *) subquery, rtoffset, 0);
 
+			/*
+			 * Upper-level vars in subquery are now one level closer to their
+			 * parent than before.
+			 */
+			IncrementVarSublevelsUp((Node *) subquery, -1, 1);
+
 			/*
 			 * Replace all of the top query's references to the subquery's
 			 * outputs with copies of the adjusted subtlist items, being