diff --git a/src/backend/parser/parse_cte.c b/src/backend/parser/parse_cte.c
index f4f7041ead..8333fca510 100644
--- a/src/backend/parser/parse_cte.c
+++ b/src/backend/parser/parse_cte.c
@@ -730,16 +730,15 @@ makeDependencyGraphWalker(Node *node, CteState *cstate)
 				 * In the non-RECURSIVE case, query names are visible to the
 				 * WITH items after them and to the main query.
 				 */
-				ListCell   *cell1;
+				List	   *new_cte_list = NIL;
 
-				cstate->innerwiths = lcons(NIL, cstate->innerwiths);
-				cell1 = list_head(cstate->innerwiths);
+				cstate->innerwiths = lcons(new_cte_list, cstate->innerwiths);
 				foreach(lc, stmt->withClause->ctes)
 				{
 					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
 
 					(void) makeDependencyGraphWalker(cte->ctequery, cstate);
-					lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
+					new_cte_list = lappend(new_cte_list, cte);
 				}
 				(void) raw_expression_tree_walker(node,
 												  makeDependencyGraphWalker,
@@ -1006,16 +1005,15 @@ checkWellFormedRecursionWalker(Node *node, CteState *cstate)
 				 * In the non-RECURSIVE case, query names are visible to the
 				 * WITH items after them and to the main query.
 				 */
-				ListCell   *cell1;
+				List	   *new_cte_list = NIL;
 
-				cstate->innerwiths = lcons(NIL, cstate->innerwiths);
-				cell1 = list_head(cstate->innerwiths);
+				cstate->innerwiths = lcons(new_cte_list, cstate->innerwiths);
 				foreach(lc, stmt->withClause->ctes)
 				{
 					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
 
 					(void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
-					lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
+					new_cte_list = lappend(new_cte_list, cte);
 				}
 				checkWellFormedSelectStmt(stmt, cstate);
 				cstate->innerwiths = list_delete_first(cstate->innerwiths);
diff --git a/src/test/regress/expected/with.out b/src/test/regress/expected/with.out
index c519a61c4f..9b04f8cba7 100644
--- a/src/test/regress/expected/with.out
+++ b/src/test/regress/expected/with.out
@@ -1852,6 +1852,21 @@ SELECT * FROM t;
  10
 (55 rows)
 
+WITH RECURSIVE j(x) AS (
+  WITH outermost(x) AS (
+    SELECT (
+      WITH innermost as (SELECT 1)
+        SELECT * FROM innermost
+    )
+  )
+  SELECT * FROM outermost
+)
+SELECT * FROM j;
+ x 
+---
+ 1
+(1 row)
+
 --
 -- test WITH attached to intermediate-level set operation
 --
diff --git a/src/test/regress/sql/with.sql b/src/test/regress/sql/with.sql
index f4ba0d8e39..72869b4bf8 100644
--- a/src/test/regress/sql/with.sql
+++ b/src/test/regress/sql/with.sql
@@ -871,6 +871,17 @@ WITH RECURSIVE t(j) AS (
 )
 SELECT * FROM t;
 
+WITH RECURSIVE j(x) AS (
+  WITH outermost(x) AS (
+    SELECT (
+      WITH innermost as (SELECT 1)
+        SELECT * FROM innermost
+    )
+  )
+  SELECT * FROM outermost
+)
+SELECT * FROM j;
+
 --
 -- test WITH attached to intermediate-level set operation
 --
