hibernate/hibernate-orm · error · SemanticException

'WITHIN GROUP' clause is illegal for non-aggregate function:

Error message

'WITHIN GROUP' clause is illegal for non-aggregate function: {functionName}

What it means

Error "'WITHIN GROUP' clause is illegal for non-aggregate function: {functionName}" thrown in hibernate/hibernate-orm.

Source

Thrown at hibernate-core/src/main/java/org/hibernate/query/hql/internal/SemanticQueryBuilder.java:4723

			);
		}
		else {
			if ( safeModeEnabled && "sql".equals( functionName ) ) {
				failIfSafeModeEnabled( safeModeEnabled, functionName, query );
			}
			final var functionKind = functionTemplate.getFunctionKind();
			if ( ctx.filterClause() != null && functionKind == FunctionKind.NORMAL ) {
				throw new SemanticException( "'FILTER' clause is illegal for non-aggregate function: "
						+ functionName,
						query );
			}
			if ( ctx.overClause() != null && functionKind == FunctionKind.NORMAL ) {
				throw new SemanticException( "'OVER' clause is illegal for non-aggregate function: "
						+ functionName,
						query );
			}
			if ( ctx.withinGroupClause() != null && functionKind == FunctionKind.NORMAL ) {
				throw new SemanticException( "'WITHIN' GROUP clause is illegal for non-aggregate function: "
						+ functionName,
						query );
			}
			if ( ctx.overClause() == null && functionKind == FunctionKind.WINDOW ) {
				throw new SemanticException( "'OVER' clause is mandatory for window-only function: "
						+ functionName,
						query );
			}
			if ( ctx.withinGroupClause() == null && ctx.overClause() == null
					&& functionKind == FunctionKind.ORDERED_SET_AGGREGATE ) {
				throw new SemanticException( "'WITHIN GROUP' or 'OVER' clause is mandatory for ordered set aggregate function: "
						+ functionName,
						query );
			}

			if ( ctx.nullsClause() != null ) {
				switch ( functionName ) {
					case "lag":

View on GitHub (pinned to fad1729dce)

Solutions

  1. WITHIN GROUP is only legal for ordered-set aggregate functions. Remove the WITHIN GROUP clause or use an ordered-set aggregate such as listagg or percentile_cont.

When it happens

Trigger: An aggregate/window clause is applied to a function that does not accept it: 'WITHIN GROUP' clause is illegal for non-aggregate function: <value>

Common situations: HQL queries that attach FILTER, OVER, WITHIN GROUP, RESPECT/IGNORE NULLS, or FROM FIRST/LAST to functions that are not aggregate or window functions, or omit a mandatory OVER/WITHIN GROUP clause.


AI-assisted analysis of hibernate/hibernate-orm@fad1729dce (2026-08-22). Data as JSON: /api/errors/c2bca9c9e2d60e5f. Report an issue: GitHub.