{"record":{"id":"c126547acccbe301","repo":"prestodb/presto","slug":"nested-window","errorCode":"NESTED_WINDOW","errorMessage":"Cannot nest window functions inside aggregation '%s': %s","messagePattern":"Cannot nest window functions inside aggregation '(.+?)': (.+?)","errorType":"error_code","errorClass":"SemanticException","httpStatus":null,"severity":"error","filePath":"presto-main-base/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java","lineNumber":404,"sourceCode":"                    }\n                }\n                if (!node.getWindow().isPresent()) {\n                    List<FunctionCall> aggregateFunctions = extractAggregateFunctions(\n                            analysis.getFunctionHandles(),\n                            node.getArguments(),\n                            functionAndTypeResolver);\n                    List<FunctionCall> windowFunctions = extractWindowFunctions(node.getArguments());\n\n                    if (!aggregateFunctions.isEmpty()) {\n                        throw new SemanticException(NESTED_AGGREGATION,\n                                node,\n                                \"Cannot nest aggregations inside aggregation '%s': %s\",\n                                node.getName(),\n                                aggregateFunctions);\n                    }\n\n                    if (!windowFunctions.isEmpty()) {\n                        throw new SemanticException(NESTED_WINDOW,\n                                node,\n                                \"Cannot nest window functions inside aggregation '%s': %s\",\n                                node.getName(),\n                                windowFunctions);\n                    }\n\n                    if (node.getOrderBy().isPresent()) {\n                        List<Expression> sortKeys = node.getOrderBy().get().getSortItems().stream()\n                                .map(SortItem::getSortKey)\n                                .collect(toImmutableList());\n                        if (node.isDistinct()) {\n                            List<FieldId> fieldIds = node.getArguments().stream()\n                                    .map(NodeRef::of)\n                                    .map(columnReferences::get)\n                                    .filter(Objects::nonNull)\n                                    .flatMap(Collection::stream)\n                                    .collect(toImmutableList());\n                            for (Expression sortKey : sortKeys) {","sourceCodeStart":386,"sourceCodeEnd":422,"githubUrl":"https://github.com/prestodb/presto/blob/55bb57d202de3b926896fa966c2c4a44c779634e/presto-main-base/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java#L386-L422","documentation":"AggregationAnalyzer.visitFunctionCall rejects window functions (OVER ...) nested inside an aggregate function's arguments. Window functions are computed after aggregation, so appearing inside an aggregate argument is invalid; throws NESTED_WINDOW with the outer aggregate name and inner window calls.","triggerScenarios":"Queries like sum(row_number() OVER (PARTITION BY x ORDER BY y)) or count(sum(x) OVER ()), where extractWindowFunctions finds window FunctionCalls among the aggregate's arguments.","commonSituations":"Attempting to total a running/ranking value; misreading evaluation order of window vs aggregate functions; generated SQL wrapping aggregates around analytic expressions.","solutions":["Compute the window function in a subquery/CTE first, then aggregate its result in the outer query","If you wanted a window over an aggregate, apply the aggregate in GROUP BY and then OVER () on the aggregated value in an outer SELECT","Remove the OVER clause if the inner function was meant to be a plain aggregate argument"],"exampleFix":"// before\nSELECT sum(row_number() OVER (ORDER BY order_date)) FROM orders\n// after\nSELECT sum(rn) FROM (SELECT row_number() OVER (ORDER BY order_date) AS rn FROM orders) t","handlingStrategy":"validation","validationCode":"// reject window functions inside aggregate arguments before executing\nboolean windowInsideAggregate = containsWindowFunctionInsideAggregateCall(expression); // AST walk\nif (windowInsideAggregate) throw new IllegalArgumentException(\"window function inside aggregate\");","typeGuard":null,"tryCatchPattern":"catch (SemanticException e) { if (e.getCode() == NESTED_WINDOW) { /* hoist window into subquery, aggregate outside */ } throw e; }","preventionTips":["Remember window functions evaluate after aggregation; never nest them inside aggregates","Use subqueries/CTEs to layer window and aggregate computations","Lint SQL for OVER(...) appearing inside aggregate parentheses","Cover window+aggregate combinations in query tests"],"tags":["sql","window-functions","aggregation","semantic-analysis","presto"],"backgroundTag":"nested-aggregation-not-allowed","analyzedSha":"55bb57d202de3b926896fa966c2c4a44c779634e","analyzedAt":"2026-09-04T12:50:26.162Z","contentChangedAt":"2026-09-04T12:50:26.162Z","schemaVersion":2},"datasetVersion":"2026-09-11T21:17:09.523Z"}