diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 823d3b445a786215da1c747a56a208110bb35a6a..7085035c525e12f761b0111ffda7eae006140eec 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -26,6 +26,7 @@
 
 #include "access/sysattr.h"
 #include "catalog/pg_type.h"
+#include "miscadmin.h"
 #include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
 #include "optimizer/var.h"
@@ -1487,6 +1488,9 @@ transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
 
 	Assert(stmt && IsA(stmt, SelectStmt));
 
+	/* Guard against stack overflow due to overly complex set-expressions */
+	check_stack_depth();
+
 	/*
 	 * Validity-check both leaf and internal SELECTs for disallowed ops.
 	 */