hibernate/hibernate-orm · error · SemanticException

'WITHIN GROUP' or 'OVER' clause is mandatory for ordered set

Error message

'WITHIN GROUP' or 'OVER' clause is mandatory for ordered set aggregate function: {functionName}

What it means

Error "'WITHIN GROUP' or 'OVER' clause is mandatory for ordered set aggregate function: {functionName}" thrown in hibernate/hibernate-orm.

Source

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

			}
			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":
					case "lead":
					case "first_value":
					case "last_value":
					case "nth_value":
						break;
					default:
						throw new SemanticException( "'RESPECT NULLS' or 'IGNORE NULLS' are illegal for function: "
								+ functionName,
								query );
				}
			}

View on GitHub (pinned to fad1729dce)

Solutions

  1. Ordered-set aggregate functions require WITHIN GROUP or OVER. Add the appropriate clause to the function call.

When it happens

Trigger: An aggregate/window clause is applied to a function that does not accept it: 'WITHIN GROUP' or 'OVER' clause is mandatory for ordered set 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/2e16b383bfa11bd0. Report an issue: GitHub.