diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index f0b053e2f6..615ed1f410 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -6155,13 +6155,19 @@ get_setop_query(Node *setOp, Query *query, deparse_context *context) Query *subquery = rte->subquery; Assert(subquery != NULL); - Assert(subquery->setOperations == NULL); - /* Need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y */ + + /* + * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y. + * Also add parens if the leaf query contains its own set operations. + * (That shouldn't happen unless one of the other clauses is also + * present, see transformSetOperationTree; but let's be safe.) + */ need_paren = (subquery->cteList || subquery->sortClause || subquery->rowMarks || subquery->limitOffset || - subquery->limitCount); + subquery->limitCount || + subquery->setOperations); if (need_paren) appendStringInfoChar(buf, '('); get_query_def(subquery, buf, context->namespaces,