diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c
new file mode 100644
index b6452e9..03a2050
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -421,12 +421,26 @@ rewriteRuleAction(Query *parsetree,
 	{
 		List	   *rtable_tail = sub_action->rtable;
 		List	   *perminfos_tail = sub_action->rteperminfos;
+		ListCell   *lc;
 
 		/*
 		 * RewriteQuery relies on the fact that RT entries from the original
 		 * query appear at the start of the expanded rtable, so we put the
-		 * action's original table at the end of the list.
+		 * action's original rtable at the end of the list.
+		 *
+		 * If there are any subquery entries in the action's original rtable
+		 * that refer to the current query level (references to NEW/OLD), then
+		 * mark those RTEs as LATERAL.
 		 */
+		foreach(lc, sub_action->rtable)
+		{
+			RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
+
+			if (rte->rtekind == RTE_SUBQUERY &&
+				contain_vars_of_level((Node *) rte->subquery, 1))
+				rte->lateral = true;
+		}
+
 		sub_action->rtable = copyObject(parsetree->rtable);
 		sub_action->rteperminfos = copyObject(parsetree->rteperminfos);
 		CombineRangeTables(&sub_action->rtable, &sub_action->rteperminfos,
